JS(4):记录一下这个坑货:mouseleave事件

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

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

JS(4):记录一下这个坑货:mouseleave事件
这是页面上显示的样式
JS(4):记录一下这个坑货:mouseleave事件
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事件在这个属性上则会指向一个对象即触发事件时鼠标所在元素对象;


JS(4):记录一下这个坑货:mouseleave事件
这是出现bug时的mouseleave事件


JS(4):记录一下这个坑货:mouseleave事件
这个是正常的鼠标移开元素触发的mouseleave事件

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


JS(4):记录一下这个坑货:mouseleave事件


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