javascript – 有没有办法保持execCommand(“insertHTML”)在chrome中删除属性?

前端之家收集整理的这篇文章主要介绍了javascript – 有没有办法保持execCommand(“insertHTML”)在chrome中删除属性?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
背景是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>
原文链接:https://www.f2er.com/js/149933.html

猜你在找的JavaScript相关文章