当前位置: 代码迷 >> 综合 >> mouseenter(mouseleave)与 mouseover(mouseout)的区别
  详细解决方案

mouseenter(mouseleave)与 mouseover(mouseout)的区别

热度:64   发布时间:2023-11-10 09:18:53.0

博主目前在蚂蚁集团-体验技术部,AntV/S2 是博主所在团队的开源项目——多维交叉分析表格,欢迎使用,感谢到 S2 github 仓库点赞 star,有任何关于前端面试、就业、技术问题都可给在文章后留言。

表象上讲,mouseenter(mouseleave)只会在元素本身触发,不会在子元素触发;mouseover(mouseout)不仅会在元素本身触发,还会在子元素触发。
原理上讲,当指针设备(通常为鼠标)移动到(离开)绑有事件监听器的元素上时,mouseenter(mouseleave)事件会被触发,和 mouseover(mouseout)事件类似,但不同的是 mouseenter(mouseleave)不会冒泡,并且当鼠标从它的子元素移动它自身元素时,不会触发 mouseenter(从自身元素离开到子元素时,也不会触发mouseleave)。而对于 mouseover(mouseout),它会从触发节点找到 DOM 树中最深层的元素,然后从这个元素开始向上传递上去,直到被组织冒泡或达到根节点。
注意:mouseover(mouseout)比 mouseenter(mouseleave)先触发。
补充:mousemove:鼠标在元素上移动时触发,在子元素上移动时也会触发。
测试代码:

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>mouse event</title>
</head>
<body><div class="a">A<div class="b"onmouseenter="mouseenter()"onmouseleave="mouseleave()"onmouseover="mouseover()"onmouseout="mouseout()"onmousemove="mousemove()">B<div class="c">C</div></div></div><script>const mouseenter = () => {
      console.log("mouseenter...");}const mouseleave = () => {
      console.log("mouseleave...");}const mouseover = () => {
      console.log("mouseover...");}const mouseout = () => {
      console.log("mouseout...");}const mousemove = () => {
      console.log("mousemove...");}</script><style>.a {
      height: 500px;width: 500px;background-color: aqua;}.b {
      height: 300px;width: 300px;background-color: burlywood;}.c {
      height: 150px;width: 150px;background-color: darkcyan;}</style>
</body>
</html>

博主水平有限,若发现文中存在问题,欢迎留言指正!

学习之路永无止境!
  相关解决方案