开发者

Can't capture first onkeypress event in JavaScript/jQuery when contenteditable=true

Here is the code:

<div onclick="this.setAttribute('contenteditable', 'true');"
    onkeypress="console.info(event.keyCode)">foo</div>
开发者_开发知识库

This is how I expected to work: user clicks a div, it is editable, then I may intercept some key events to run customized handling with Enter, Tab, Arrow keys.

The problem is, you can edit the div after click, but you can not get the first key press event from onkeypress. You can only get a keypress event if you press twice.

I am using Chrome Dev v12 on Win7 32 bit. Please help


Try adding this.focus like this:

<div onclick="this.setAttribute('contenteditable', 'true');this.focus();"
onkeypress="console.info(event.keyCode)">foo</div>

I have tried here http://jsfiddle.net/carlesandres/At9uK/ and it worked.


You could do this (jquery way):

<div id="div1"> foo </div>

<script>
$(document).ready(function(){
   $("#div1").click(function(){
      $(this).attr("contenteditable", true);
   }).keypress(function(event){
      console.info(event.keyCode);
   });
});
</script>

Hope this helps. Cheers

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜