5
我有一個div的contenteditable屬性已被設置爲true。我如何讓孩子們迴應鍵盤事件?似乎唯一的辦法是捕捉父div中的事件並通過選擇apis找出孩子。有沒有更好的辦法?更具體地說,我可以將鍵盤事件處理程序附加到子元素嗎?我錯過了什麼嗎?在contenteditable div中的子元素的鍵盤事件?
附加是說明問題的示例代碼。希望代碼中的評論足夠說明問題。
<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>