当父元素设置为contentEditable时,是否有可能防止子元素被删除?

7

当一个元素被设置为 contentEditable 后,它的子元素可以被删除。如果其中一个子元素没有设置为 contentEditable,则不能编辑该子元素的内容,但是该元素本身仍然可以被删除。您可以在以下示例中查看此示例。

有没有可能防止这些子元素被删除?

div {
  height: 100px;
  border: 1px solid #CCC;
  margin: 5px;
  padding: 5px;
  width: 300px;
}

span {
  color: #999;
}
<div contentEditable="true">Hello <span contentEditable="false">world</span>!</div>


好问题!我能想到的唯一方法就是创建单独的div,并将外部标记为contentEditable:<div><span contentEditable="true">你好</span><span contentEditable="false">世界</span><span contentEditable="true">!</span></div> - Blue
谢谢您的建议。虽然从技术上讲这是可行的,但会导致用户体验繁琐,而我希望避免这种情况。 - Nathanael
2个回答

0
如果您可以使用类,那么这将变得很容易。
<div class="contentEditable">Hello <span class="contentNotEditable">world</span>!</div>
<div class="saveContent" style="display: none;"></div>

JavaScript/JQuery部分

<script>
$(".contentEditable").on("click",function(){
 // make blank .saveContent
 $(".saveContent").html("");

 // copy all contentNotEditable class which inside selected contentEditable class.
 $( this ).find(".contentNotEditable").clone().appendTo( ".saveContent" );

 // make blank contentEditable
 $( this ).html("");

 // clone contentNotEditable to contentEditable
 $( ".saveContent" ).find(".contentNotEditable").clone().appendTo( ".contentEditable" );
});
</script>

它在我的测试中运行良好。但是它需要jquery。当您单击.contentEditable区域时,它仅显示contentNotEditable区域。 - Fatihd
@Fatihd 你应该在一个可工作的代码片段中展示它。 - Blue

0
这些子元素能否被防止删除?
不行,但是这里有一个替代方案。
演示:
由于我们不能直接拥有子元素,所以我们需要创建两个单独的元素。
<div class="editor">
  <label class="editor-label">You can't remove me</label>
  <div class="editor-area" contentEditable="true"></div>
</div>


然后,我们从流程中删除标签,以便它不会对区域产生任何影响。

.editor {
  border: solid 1px #CCC;
  position: relative; // context for label
  line-height: 1.5;
}

.editor-area {
  min-height: 100px;
  padding: 5px;
}

.editor-label {
  position: absolute; // out of the flow
  padding: 5px 0 0 5px;
  user-select: none;
}

最后,为了使插入符号在标签文本之后开始,我们需要知道其宽度并将其应用于区域text-indent值。
var editorLabel = document.querySelector('.editor-label');
var editorArea = document.querySelector('.editor-area');

var editorLabelRect = editorLabel.getBoundingClientRect();

editorArea.style.textIndent = editorLabelRect.width + 'px';
editorArea.innerHTML = '&nbsp';

完整代码:

var editorLabel = document.querySelector('.editor-label');
var editorArea = document.querySelector('.editor-area');

var editorLabelRect = editorLabel.getBoundingClientRect();

editorArea.style.textIndent = editorLabelRect.width + 'px';
editorArea.innerHTML = '&nbsp';
.editor {
  border: solid 1px #CCC;
  position: relative;
  line-height: 1.5;
}

.editor-area {
  min-height: 100px;
  padding: 5px;
}

.editor-label {
  position: absolute;
  margin: 5px 0 0 5px;
  user-select: none;
}
<div class="editor">
  <label class="editor-label">You can't remove me</label>
  <div class="editor-area" contentEditable="true"></div>
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接