开发者

How do you get a focus or keypress event inside the children of a div set to contenteditable true?

I am trying to use event delegation inside a containing div tag set to contenteditable. For focus and keypress events the event is captured by the element with the contenteditable set to true. I want the element that the event happened on to be returned. Is there anyway for the event to register on the element you开发者_如何学编程 are actually working on without attaching events to each one, or setting every element to contenteditable="true"? If you click on any of the element d1 it returns element top not d1.

<div id="top" contenteditable="true">
<div id="d1">Edit</div>
<div id="d2">Edit</div>
<div id="d3">Edit</div>
</div>

window.onload=function(){
document.getElementById('top').addEventListener('focus',function(e){
  console.log(e.target);
},true);
}


I don't know how to do this in pure js, but I know it can be done in jQuery using .closest()

Even if you don't want to use jQuery, you may search for how it works. Good luck!

Edit:

I've just tested the code here in Opera... Don't know if it's a bug, tough... But using to 'click' instead of 'focus' make it correctly get the id of the inner div

Take a look:

<script type="text/javascript">
window.onload = function(){
  document.getElementById('top').addEventListener('click',function(e){
    alert(e.srcElement.id); //this alert d1 to d3
  },true);
document.getElementById('top').addEventListener('focus',function(e){
    alert(e.srcElement.id); //this alert top
  },true);
}
</script>

<div id="top" contenteditable="true">
      <div id="d1">Edit</div>
      <div id="d2">Edit</div>
      <div id="d3">Edit</div>
</div>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜