上代码:
<style> div { margin: 0 auto; } .box { box-sizing: border-box; padding: 30px 0; width: 300px; border: 1px solid #005AA0; } .sonBox { width: 150px; height: 150px; background-color: #00823C; } </style> <div class="box"> <div class="sonbox"></div> </div> <script type="text/javascript"> var box = document.getElementsByClassName("box")[0]; box.addEventListener("mouseenter",function(){ console.log("MouseEnter!"); }); box.addEventListener("mouseover",function(){ console.log("MouseOver!"); }); box.addEventListener("mouseout",function(){ console.log("MouseOut!"); }); box.addEventListener("mouseleave",function(){ console.log("MouseLeave!"); }); </script>
如上面建一个div类名为box里面有个子div.sonbox,测试一下当我们鼠标穿过整个box会打印什么,结果如下图示:
总结:
1、mouseover和mouseout在父元素和其子元素都可以触发,当鼠标穿过一个元素时,触发次数得依子元素数量而言。
2、mouseenter和mouseleave只在父元素触发,当鼠标穿过一个元素时,只会触发一次。
3、mouseover和mouseout比mouseenter和mouseleave先触发
因此一般mouseover和mouseout一起使用,mouseenter和mouseleave一起使用,而使用场景通过上面的解析,大家也该心中有数了吧。