可编辑div中子元素的键盘事件?

6

我有一个div元素,其contenteditable属性被设置为true。如何使子元素响应键盘事件?似乎唯一的方法是在父div中捕获事件,并通过选择API找到子元素。是否有更好的方法?更具体地说,我能否将键盘事件处理程序附加到子元素?我错过了什么吗?

下面是演示问题的示例代码。希望代码中的注释足够清楚易懂。

<HTML>
<HEAD>
<TITLE></TITLE>
</HEAD>

<BODY>
<div id="editable" contentEditable='true' style='height: 130px; width: 400px; border-style:solid; border-width:1px'>
    <span id="span1" onkeypress="alert('span1 keypress')">test text 1</span> <!-- does not work -->
    <span id="span2" > test text2</span>
    <span id="span3" onclick="alert('span3 clicked')">test text 3</span>  <!-- this works fine -->
</div>
<!-- Uncomment this to set a keypress handler for span2 programatically. still doesnt work -->
<!--
<script type="text/javascript">
    var span2 = document.getElementById('span2');
    span2.onkeypress=function() {alert('keypressed on ='+this.id)};
</script>
-->

<!-- Uncomment this to enable keyboard events for the whole div. Finding the actual child that the event is happening on requires using the selection api -->
<!--
<script type="text/javascript">
    var editable = document.getElementById('editable');
    editable.onkeypress=function() {alert('key pressed on ='+this.id+';selnode='+getSelection().anchorNode.parentNode.id+',offset='+getSelection().getRangeAt(0).startOffset)};
</script>
-->
</BODY>
</HTML>
1个回答

3
这是因为普通的
无法接收焦点。您可以通过向标签添加tabindex属性或使其可编辑来使普通的
具有焦点。您不希望在子上使用tabindex,因为这似乎会防止IE中的编辑。我本来想建议检查整个
keypress处理程序传递的对象的target / srcElement属性,但在IE中,这只会给您一个对相同
的引用,而不是子

所以回答您的问题,我认为没有比使用选择更好的跨浏览器解决方案来检查字符输入的位置。


你能提供一个例子吗? - SREERAG R NANDAN

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