contenteditable div中的子元素的键盘事件?

时间:2009-06-23 14:43:27

标签: keyboard-events contenteditable

我有一个div,其中contenteditable属性设置为true。如何让孩子们回应键盘事件?似乎唯一的方法是捕获父div中的事件并通过选择apis找出孩子。有没有更好的办法?更具体地说,我可以将键盘事件处理程序附加到子元素吗?我错过了什么吗?

附件是说明问题的示例代码。希望代码内的注释充分解释。

<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 个答案:

答案 0 :(得分:3)

这是因为常规跨距和div无法获得焦点。您可以通过向标记添加tabindex属性或使其可编辑来使正常范围或div可聚焦。您不希望子跨度上有tabindex,因为这似乎阻止它在IE中可编辑。我打算建议检查传递给整个div的target处理程序的srcElement Event对象的keypress / {{1}}属性,但是在IE中这只给你一个参考相同的div而不是子跨度。

因此,在回答您的问题时,我不相信有一个更好的跨浏览器解决方案,而不是使用选择来检查字符的输入位置。