如何通过父母的onmouseover事件传递孩子?

时间:2015-12-24 23:28:04

标签: javascript html triggers onmouseover

只要鼠标进入元素或其中一个孩子,

onmouseover就会触发。有没有一种很好的方法只在父节点上设置onmouseover事件,但是它会在参数中传递当前悬停的元素(触发事件)?

 <div id="parent" onmouseover="foo(triggerElement)">  <!-- this ofc doesn't work. How to write this? -->
   <div id="child1" onmouseover="foo(this)">Child 1</div>
   <div id="child2" onmouseover="foo(this)">Child 2</div>
   <div id="child3" onmouseover="foo(this)">Child 3</div>
   <!-- I don't want to set the same onmouseover event for each child -->
 </div>

jsfiddle

我当然可以使用javascript将参数'this'添加到div的每个孩子的onmouseover属性,但这似乎不太好。有更好的方式吗?

1 个答案:

答案 0 :(得分:1)

这样的事情应该这样做

document.getElementById('parent').addEventListener('mouseenter', function(event) {
    if (event.target !== this)
        event.target.innerHTML = "You just hovered " + event.target.id;
}, true);

FIDDLE