javascript – 专注于嵌套的contenteditable元素

所以,我有两个嵌套在另一个内部的contenteditable div:

<div class="top" contenteditable="true">
     <div class="nested" contenteditable="true">This</div>
</div>

这是Fiddle.

当它被聚焦时,应该集中嵌套,但是使用console.log(document.activeElement);它显示顶部是聚焦的,它不识别嵌套的div.

在正在编辑内容的情况下,我需要识别嵌套的div元素而不是顶部元素.

我怎么做到这一点?任何帮助都感激不尽.

最佳答案 [contenteditable]元素由浏览器处理的方式使任何嵌套的[contenteditable]不处理任何事件,编辑主机是以前可编辑的父级.见
spec

If an element is editable and its parent element is not, or if an
element is editable and it has no parent element, then the element is
an editing host. Editable elements can be nested. User agents must
make editing hosts focusable (which typically means they enter the tab
order). An editing host can contain non-editable sections, these are
handled as described below. An editing host can contain non-editable sections that contain further editing hosts.

现在作为一种解决方法,您可以通过将其任何可编辑的父级临时设置为不可编辑来使托管主机具有集中嵌套的可编辑元素.见例如:

$('div.top [contenteditable]').on('focusin focusout', function(e) {
    $(this).parents('[contenteditable]').prop('contenteditable', e.type === "focusout");
});

-updated jsFiddle-

点赞