我有一个包含 span 的 contenteditable div,并且希望在输入 div 本身和 div 内的 span 时跟踪 keydown 事件。
到目前为止,在 Firefox 中一切似乎都工作正常,但在 webkit 浏览器中,div keydown 事件似乎覆盖了 span 事件。有没有办法在 div 内触发 keydown,即使是在 span 内? (Demo)
HTML:
<div id="ceDiv" contenteditable="true" tabindex="0" onkeydown="return fnKeyDiv(event);">
put your cursor/caret in this contenteditable text and type some characters
or use the arrow keys
-- <span id="ceSpan" tabindex="0" onkeydown="return fnKeySpan(event);">
see what happens when typing inside this yellow text</span>
-- it's not clear to me : counter 2 only works when you click the mouse
inside the yellow text to put the caret there, not when the caret is moved inside
the yellow text by the arrow keys ..
AND : counter 2 does never work in WebKit !? (in FireFox it does)
</div>
<hr />
<span id="ST1" class="ST"></span> : counter 1 : typing in total text<br />
<span id="ST2" class="ST"></span> : counter 2 : typing in yellow "mytext"
JS:
var count = 0;
function fnKeyDiv(e) {
count++;
document.getElementById('ST1').innerHTML = count;
return true;
}
function fnKeySpan(e) {
count++;
document.getElementById('ST2').innerHTML = count;
return true;
}
最佳答案
我遇到了同样的问题,它似乎发生了,因为它是 div 元素捕获 keydown 事件,而不是内部 span 元素。
要让它们捕获 keydown 事件,您需要为每个容器设置 contenteditable=true,同时为 div 容器设置 contenteditable=false。
要使 div 容器和内部 Span 都捕获 keydown 事件,您可以将 Span 包装在不可编辑的 Span 中:
<div id="ceDiv" contenteditable="true" tabindex="0" onkeydown="return fnKeyDiv(event);">
keydown events here are caught
<span contenteditable="false">
<span id="ceSpan" tabindex="0" onkeydown="return fnKeySpan(event);" contenteditable="true" >
keydown events here are caught too
</span>
</span>
</div>
编辑:没关系,当您没有单击最里面的跨度时,它仍然无法工作。我不知道如何将焦点放在它上面。
编辑:如果您使用 DOM HTMLElementObject.focus() 方法将焦点设置在内部跨度上,它就会起作用。我使用的是 jQuery .focus() 方法,该方法仅触发焦点事件。
关于javascript - contenteditable div 和子跨度上的 Keydown 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22895124/