背景是Chrome 37.0.2062.120 m.
我使用execCommand将html插入到可编辑的div中.我的execCommand调用看起来像这样:
function insertHTML(){ document.execCommand('insertHTML',false,'<span id="myId">hi</span>'); }
当可编辑的div看起来像这样:
<div contenteditable="true"> some [insertion point] content </div>
并且我使用execCommand将html插入到contenteditable div中,HTML的所有属性都按预期插入,我最终会这样:
<div contenteditable="true"> some <span id="myId">hi</span> content </div>
但是,当我将完全相同的html插入到这个结构中:
<div contenteditable="true"> some content <div>more [insertion point] content</div> </div>
<div contenteditable="true"> some content <div>more <span style="font-size: 10pt;">hi</span> content</div> </div>
有什么办法可以防止这种情况发生吗?
解决方法
在这种特殊情况下,我会建议使用
Range.insertNode
,这将使您完全控制插入的内容:
function insertHTML() { var sel,range; if (window.getSelection && (sel = window.getSelection()).rangeCount) { range = sel.getRangeAt(0); range.collapse(true); var span = document.createElement("span"); span.id = "myId"; span.appendChild( document.createTextNode("hi") ); range.insertNode(span); // Move the caret immediately after the inserted span range.setStartAfter(span); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); } }
function isOrIsAncestorOf(ancestor,descendant) { var n = descendant; while (n) { if (n === ancestor) { return true; } else { n = n.parentNode; } } return false; } function nodeContainsSelection(node) { var sel,range; if (window.getSelection && (sel = window.getSelection()).rangeCount) { range = sel.getRangeAt(0); return isOrIsAncestorOf(node,range.commonAncestorContainer); } return false; } function insertHTML() { var sel,range; if (window.getSelection && (sel = window.getSelection()).rangeCount) { range = sel.getRangeAt(0); range.collapse(true); var span = document.createElement("span"); span.id = "myId"; span.appendChild( document.createTextNode("hi") ); range.insertNode(span); // Move the caret immediately after the inserted span range.setStartAfter(span); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); } } window.onload = function() { document.getElementById("inserter").onmousedown = function() { var editor = document.getElementById("editor"); if (nodeContainsSelection(editor)) { insertHTML(); return false; } }; };
span { font-weight: bold; color: green; }
<input type="button" id="inserter" value="Insert span"> <div contenteditable="true" id="editor"> some content </div>