Contenteditable:防止删除内部元素

时间:2016-12-01 01:55:41

标签: javascript jquery contenteditable

我有一个简单的可信标记:

<div class="example" contenteditable="true">
     <div class="inside">Some content</div>
</div>

当我删除“Some content”时,class="inside" div也会被删除。有没有办法防止在删除内容时删除内部div?

例如,这是我在删除内容后尝试制作的外观。

<div class="example" contenteditable="true">
     <div class="inside"></div> <!-- The div is not deleted -->
</div>

我环顾四周,但似乎没有一个明确的答案。

非常感谢任何帮助。

谢谢。

4 个答案:

答案 0 :(得分:0)

&#13;
&#13;
.inside, .example {
  display: inline;
}
&#13;
<div class="example" contenteditable="true">
  <div class="inside">Some content</div>
</div>
&#13;
&#13;
&#13;

也许有一种内联级元素的风格。

因为删除内容时宽度将为0%。您无法再次点击它或添加任何内容。

所以,我的解决方案将是

.inside, .example {
  display: block;
}

您可以根据需要指定宽度。 :)

&#13;
&#13;
.inside, .example {
  display: block;
}
&#13;
<div class="example" contenteditable="true">
  <div class="inside">Some content</div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您必须将contenteditable="true"添加到内部元素中:

<div class="example">
     <div class="inside" contenteditable="true">Some content</div>
     <div class="inside">Some content</div> <!-- This one will not be deleted -->
     <div class="inside" contenteditable="true">Some content</div>
</div>

答案 2 :(得分:0)

这可能会帮助某人

function onpaste(e: ClipboardEvent) {
  e.preventDefault();

  const selection = window.getSelection();
  // Don't allow deleting nodes
  if (selection.anchorNode.isSameNode(selection.focusNode)) {
    // get text representation of clipboard
    const text = e.clipboardData.getData("text/plain");

    // insert text manually, but without new line characters as can't support <br/>s yet
    document.execCommand("insertHTML", false, text.replace(/\n/g, ""));
  }
}

function onkeydownInEditable(e: KeyboardEvent) {
  if (e.key === "Enter") {
    e.preventDefault();
  }
  if (e.key === "Backspace" || e.key === "Delete" || e.key === "Paste") {
    const selection = window.getSelection();
    // Don't allow deleting nodes
    if (!selection.anchorNode.isSameNode(selection.focusNode))
      e.preventDefault();
  }
}

 elementEditing.addEventListener("keydown", onkeydownInEditable);
 elementEditing.addEventListener("paste", onpaste);

答案 3 :(得分:0)

List<dynamic> list1 = [/*any items*/];
List<dynamic> list2 = [/*other items*/];

List<dynamic> finalList = [...list1, ...list2].toSet().toList();