onmouseenter 和 onmouseover 的不同
首先,从英语释义来看,over表示在某个物体的上方,而enter表示进入。当然,在浏览器中,鼠标永远都在DOM元素的上面,所以,over的时候就已经enter了。
在具体的使用中,两者的效果是相似的,使用的场景并没有太大的区别,效果类似css中的hover。但是,两者还是存在一定的区别的,在大多数相关文章中都会提到一点,那就是mouseenter不支持冒泡,而mouseover支持冒泡。冒泡指的是事件冒泡,即在子元素上触发的事件会向上传递至父级元素,并触发绑定在父级元素上的相应事件。
那么,如何证明这两个事件是否支持,事件冒泡呢,js的事件机制给了我们一个很好的解决方法,那就是target(事件源),在事件触发时,浏览器会产生一个event对象,在这个对象上有一个target属性,指向了触发事件的最底层的DOM,通过target我们可以准确的找到事件触发的元素。
[HTML] 纯文本查看 复制代码
|
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>onmouseover&onmouseenter</title> <style> #outer{ position: relative; width: 200px; height: 200px; margin: 100px; border: 1px solid #ccc; } #inner{ position: absolute; left: -50px; top: 0; width: 100px; height: 100px; border: 1px solid #ccc; } </style></head><body> <div id="outer"> <div id="inner"></div> </div> <script> outer.onmouseenter = function(e){ console.log(e.target.id) // outer } outer.onmouseover = function(e){ console.log(e.target.id) // inner } </script></body></html> |
为了让不让元素的位置影响结果,我们利用定位属性将id为inner的div定位在父级元素的外部,当鼠标直接进入到它的内部时,会触发相应的事件,打印的结果就如代码所示的那样了。由此可见,mouseenter是不支持事件冒泡的,在使用的过程中,因为mouseover支持冒泡,所以在父级元素内移动时,可能会多次触发事件,建议大家谨慎使用mouseover。

浙公网安备 33010602011771号