记录一个坑:mouseleave事件

        今天在做一个弹出式下拉框时遇到了一个BUG,如下图所示,我下拉框中加入一组多选多选框,并且设置当用户的鼠标移出多选框部分的div时,多选框隐藏,这个时候当然是选择使用mouseleave事件来实现最好啦。

        可是不久后问题就来了:当我在多选框中选择项目时,时不时就会触发mouseleave事件,导致用户选着选着多选框消失,用户体验极差啊;仔细观察后,发现好像我在checkbox上的双击时,会偶然性的触发mouseleave事件,感觉就像抽奖一样。。

 
7110579-261a8c41301e4042.png
这是页面上显示的样式
 
7110579-81fe81d883023acd.png
dom结构

在经历数次搜索后,我决定看看外国人怎么解决这一问题,结果还真让我找到了:

https://stackoverflow.com/questions/47649442/click-event-effects-mouseenter-and-mouseleave-on-chrome-is-it-a-bug

I can confirm the behaviour on chrome (Version 62.0.3202.94).

When clicking an element multiple times, occasionally mouseleave is fired with a relatedTarget/toElement property of "null" on the MouseEvent (screenX, screenY properties both 0).

The behaviour is random, sometimes it needs 2 subsequent clicks, sometimes more than 20. Clicking speed/rate seems irrelevant too.

By now I avoid the execution of unwanted code in my onMouseLeave(event) method by checking the relatedTarget property of the event(if "null" do nothing). Don't know if there is another useful case where relatedTarget could be null...

这里说到:当你数次点击一个元素多次后,会偶尔触发mouseleave事件,但是这个事件有一个特点和正常触发的mouseleave事件不同,就是该事件的relatedTarget属性为null,而正常触发的mouseleave事件在这个属性上则会指向一个对象即触发事件时鼠标所在元素对象;

 

 
7110579-6e1032f385f559a0.png
这是出现bug时的mouseleave事件

 

 
7110579-fd825c6a57cc1744.png
这个是正常的鼠标移开元素触发的mouseleave事件

到这里问题解决方案就变得很清晰了,我只要对mouseleave事件进行一下过滤,只对正常触发的mouseleave事件进行响应,即可完美解决这个问题:

 

 
7110579-c25c4a9f28fe30e7.png
 

 

总结:自己对底层一些的知识还太过小白,以后真的要多加训练。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值