简单了解mouseover与mouseenter的使用场景

我们知道鼠标经过和离开的事件有俩种:

mouseenter与mouseover,那么这里俩个事件有什么区别呢?

mouseenter:给谁注册的事件,就必须经过谁,才能触发该事件

简单来说mouseenter不能冒泡,也就是说经过其子盒子,不会触发它的事件

而mouseover刚好相反,因为mouseover会冒泡。所以当你经过它的子盒子它也会触发相应事件:

<style>
    *{
        margin: 0;
        padding: 0;
    }
    div{
        position: relative;
        margin-top: 50px;
        margin-left: 50px;
        width: 300px;
        height: 300px;
        background-color: aquamarine;
    }
    a{
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%,-50%);
        display: block;
        width: 100px;
        height: 100px;
        border: 5px solid #000;
        padding: 5px;
        background-color: brown;
    }
    em{
        position: absolute;
        top: 5000px;
    }
</style>
<body>
    <div><a href="javascript:;">son</a>father</div>
</body>
<script>
const div = document.querySelector('div')
const a = document.querySelector('a')
div.addEventListener('mouseover',function(){
    console.log('触发了div');
    this.style.backgroundColor = 'blue'
})
</script>

当鼠标经过son时,必然会先经过father,经过father触发了一次,经过son因为冒泡原理又触发了一次father:

 

 如果我们使用mouseenter呢?

const div = document.querySelector('div')
const a = document.querySelector('a')
div.addEventListener('mouseenter',function(){
    console.log('触发了div');
    this.style.backgroundColor = 'blue'
})

当鼠标经过son时,必然会先经过father,经过father触发了一次,经过son之后,因为mouseenter不能冒泡,所以没有触发father:

我们可以根据实际情况来判断到底使用哪种鼠标经过事件 

mouseenter --> 鼠标经过(不冒泡)mouseleave -->鼠标离开(不冒泡)
mouseover -->鼠标经过(冒泡)mouseout -->鼠标离开(冒泡)
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Try Tomato

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值