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()
})
如下图所示就只有移出,没有移入了
以上是个人愚见,如有错误请大牛不吝赐教!