js 鼠标事件mouseover和mouseout在父盒子移到子盒子中的思考

mouseover事件一般不推荐使用不过最近遇到了一个问题,就思考了一下。
在这里插入图片描述
如上图所示:
HTML代码如下

  <div class="father">
        <div class="son"></div>
    </div>

js代码

var father = document.querySelector('.father')
var son = document.querySelector('.son')
father.addEventListener('mouseover',function(e){
    console.log("移入了")
  
})

father.addEventListener('mouseout',function(e){
    console.log("移出了")
   
})

从父盒子移动到子盒子过程中先打印移出在打印移入。
原因思考:
1、鼠标移动到子盒子上,浏览器默认鼠标离开父盒子了所以打印“移出”,但是已经移到子盒子中,在子盒子中有移入事件,但是没有事件对应函数,然后事件冒泡给了父盒子,父盒子有mouseover事件对应函数,所以打印了“移入”。犹豫有一个冒泡过程所以先打印“移出”在打印与“移入”。
为了验证猜想:
js代码添加阻止冒泡事件

var father = document.querySelector('.father')
var son = document.querySelector('.son')
father.addEventListener('mouseover',function(e){
    console.log("移入了")
   
  
})

father.addEventListener('mouseout',function(e){
    console.log("移出了")
  
})


son.addEventListener('mouseover',function(e){
    // console.log("son移入了");
    e.stopPropagation()
})

son.addEventListener('mouseout',function(e){
    // console.log("son移出了")
 e.stopPropagation()
})

如下图所示就只有移出,没有移入了
在这里插入图片描述
以上是个人愚见,如有错误请大牛不吝赐教!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值