2009-06-23 20 views
5

私はcontentableプロパティがtrueに設定されているdivを持っています。どのように子供たちがキーボードイベントに応答するようにしますか?唯一の方法は、親div内のイベントをキャプチャし、選択apiを介して子供を把握することです。より良い方法がありますか?具体的には、キーボードイベントハンドラを子要素にアタッチすることはできますか?何か不足していますか?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> 

答えて

3

通常のスパンとdivはフォーカスを受け取ることができないためです。タグにtabindex属性を追加するか、編集可能にすることで、通常のスパンまたはdivにフォーカスを合わせることができます。子スパンにはtabindexが必要ではありません。IEで編集できないように思われるからです。私は、Eventオブジェクトの/srcElementプロパティを調べて、div全体のkeypressハンドラに渡すことを提案しようとしていましたが、IEではこれは子スパンではなく同じdivへの参照のみを提供します。

あなたの質問に答えて、文字をどこに入力したかをチェックするために選択肢を使用するよりも、ブラウザ間のソリューションが優れているとは思いません。

関連する問題