有没有办法让execCommand(" insertHTML")不去除chrome中的属性?

时间:2014-09-19 20:00:12

标签: javascript contenteditable execcommand

上下文是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插入到一个可信的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>

有没有办法防止这种情况发生?

2 个答案:

答案 0 :(得分:19)

在这种特殊情况下,我建议使用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>

答案 1 :(得分:1)

一种解决方案可能是不使用span,即使用非span元素。我使用过bootstrap元素&#34;&#34;相反,为了解决与Chrome类似的问题,因为斜体对我来说很好 - 结果是 - 愚蠢的&#34; bug&#34;在Chrome中不会影响我。请参阅此处的讨论:Discussion re CKEdit bug, but relevant here too