在 Contenteditable Div 中的插入符號處插入 Html
在 contenteditable div 中,捕獲按鍵可以防止插入不需要的字元。這就提出了直接插入 HTML 元素的要求,例如
標籤。雖然為 contenteditable div 中的文字插入提供的解決方案在 IE 中使用 range.pasteHTML 方法工作,但它在其他瀏覽器中將
標籤呈現為純文字。
使用 insertNode() 插入 HTML
在大多數瀏覽器中,您可以利用從選取範圍取得的 Range 的 insertNode() 方法來插入 HTML 節點。 IE 9以下版本仍然支援pasteHTML()。
插入HTML的函數
以下函數可用於在所有主流瀏覽器中插入HTML:
function pasteHtmlAtCaret(html) { var sel, range; if (window.getSelection) { sel = window.getSelection(); 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); } } } else if (document.selection && document.selection.type != "Control") { document.selection.createRange().pasteHTML(html); } }
更新:選擇插入的內容
對於插入後想要選擇插入內容的場景,可以使用附加參數更新函數,如下所示:
function pasteHtmlAtCaret(html, selectPastedContent) { // Implementation with logic for selecting the inserted content if selectPastedContent is true }
以上是如何在 ContentEditable Div 的插入符處插入 HTML?的詳細內容。更多資訊請關注PHP中文網其他相關文章!