如何检测何时通过键盘编辑了一个可信的DIV的子元素?

Šim*_*das 11 html javascript contenteditable

鉴于此HTML代码:

<div contenteditable>
    ....
    <span> child-element </span>
    ....
</div>
Run Code Online (Sandbox Code Playgroud)

当用户点击SPAN元素上(为了把里面的尖号),然后在键盘上按下一个字符键(以编辑SPAN元素的文本内容),一个keydown,keypresskeyup事件会被解雇.

但是,target那些相应事件对象的属性不是 SPAN元素,而是DIV元素本身.

现场演示:(也在jsFiddle上)

$('div').keydown(function(e) {
    alert( e.target.nodeName );
});
Run Code Online (Sandbox Code Playgroud)
div { border:2px solid red; padding:10px; margin:10px; }
span { background-color:yellow; }
Run Code Online (Sandbox Code Playgroud)
<div contenteditable>
    BEFORE
    <span>SPAN</span>
    AFTER
</div>

<p>
    Click on the yellow SPAN element (to place the caret inside it), and then press a character key (to change the text-content of the SPAN element). The alert-box shows that the event-target is the DIV element, not the SPAN element...
</p>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

如何确定键事件是否发生在SPAN元素内?

Way*_*ett 13

这可以使用选择API完成:

$('div').keydown(function(e) {
    if (document.selection) {
        alert(document.selection.createRange().parentElement().tagName); // IE
    } else {
        // everyone else
        alert(window.getSelection().anchorNode.parentNode.tagName); 
    }
});
Run Code Online (Sandbox Code Playgroud)

注意:上面的例子很简单.请参阅下面链接的SO帖子,以获得选择问题的完整解决方案.

演示(也在jsFiddle上):

$('div').keydown(function(e) {
    if (document.selection)
        alert(document.selection.createRange().parentElement().tagName); // IE
    else
        alert(window.getSelection().anchorNode.parentNode.tagName); // everyone else
});
Run Code Online (Sandbox Code Playgroud)
div { border:2px solid red; padding:10px; margin:10px; }
span { background-color:yellow; }
Run Code Online (Sandbox Code Playgroud)
<div contenteditable>
    BEFORE
    <span>SPAN</span>
    AFTER
</div>

<p>
    Click on the yellow SPAN element (to place the caret inside it), and then press a character key (to change the text-content of the SPAN element). The alert-box shows that the event-target is the DIV element, not the SPAN element...
</p>
<div id="stuff"/>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

参考文献: