contenteditable插入及粘贴纯文本内容 contenteditable="true"元素过滤富文本样式 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>contenteditable</title> <style> #insert{ width: 90px; height: 30px; border: 1px solid #ccc; background-color: #fff; margin: 10px; } #editor{ padding: 10px; overflow-y: auto; min-height:200px; border:1px solid #f33; outline: 0; } #editor h4{ margin: 10px 0; } </style> </head> <body> <button type="button" id='insert'>插入标题</button> <div contentEditable="true" id="editor"> <h3>副标题</h3> <p>文本</p> </div> </body> <script> document.getElementById('insert').onclick=function(){ var content = prompt('请输入内容'); document.getElementById('editor').focus(); if(!!content){ insertHtmlAtCaret('<h4>'+content+'</h4>'); } } document.getElementById('editor').onpaste=function(event){ var e = event || window.event e.preventDefault(); var text = (e.originalEvent || e).clipboardData.getData('text/plain') || prompt('在这里输入文本'); document.execCommand("insertText", false, text); }; function insertHtmlAtCaret(html) { var sel = window.getSelection(), range; if (sel.getRangeAt && sel.rangeCount) { range = sel.getRangeAt(0); range.deleteContents(); var el = document.createElement("div"); el.innerHTML = html; var frag = document.createDocumentFragment(), node, lastNode; while ( (node = el.firstChild) ) { lastNode = frag.appendChild(node); } range.insertNode(frag); if (lastNode) { range = range.cloneRange(); range.setStartAfter(lastNode); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); } } } </script> </html> _pasteHandle: function () { const editor = this.editor const $textElem = editor.$textElem $textElem.on('paste', function (e) { const clipboardData = e.clipboardData || (e.originalEvent && e.originalEvent.clipboardData) let pasteText if (clipboardData == null) { pasteText = window.clipboardData && window.clipboardData.getData('text') } else { pasteText = clipboardData.getData('text/plain') } e.preventDefault() document.execCommand('insertText', false, pasteText) }) }
评论 (0 )
最新评论
暂无评论
赶紧努力消灭 0 回复