我有一个包含跨度的contenteditable div,并且想要在div本身和div中的span中输入时跟踪keydown事件。
到目前为止,在firefox中似乎一切正常,但在webkit浏览器中,div keydown事件似乎覆盖了span事件。有没有办法解雇keydown,即使是在跨越div的范围内? (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;
}
答案 0 :(得分:3)
我遇到了同样的问题而且似乎发生了,因为它是捕获keydown事件的div元素,而不是内部span元素。
要使它们捕获keydown事件,您需要为每个事件设置contenteditable = true,同时为div容器设置contenteditable = false。
要使div容器和内部span都能捕获keydown事件,您可以将跨度包装在不可编辑的范围内:
<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()方法,只有触发焦点事件。