Tôi có một div thuộc tính có thể chỉnh sửa được đặt thành true.Tôi làm cách nào để các con trả lời các sự kiện bàn phím? Có vẻ như cách duy nhất là nắm bắt các sự kiện trong div cha và tìm ra con thông qua apis lựa chọn. Có cách nào tốt hơn? Cụ thể hơn, tôi có thể đính kèm trình xử lý sự kiện bàn phím cho các phần tử con không? Tui bỏ lỡ điều gì vậy?Sự kiện bàn phím cho các phần tử con trong div có thể chỉnh sửa được?
Đính kèm là mã mẫu minh họa sự cố. Hy vọng các ý kiến trong mã là đủ giải thích.
<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>