今天练习用原生JS写物体运动的时候,发现一个事情,那就一直大家认为的不能冒泡的mouseenter,和mouseleave,冒泡了,而且一冒就停不下来。先上代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.wrapper {
width: 400px;
height: 80px;
background-color: black;
position: absolute;
left: -400px;
top: 300px;
}
.show {
position: absolute;
right: 40px;
top: 0px;
right: -40px;
height: 80px;
width: 40px;
background-color: orange;
}
</style>
</head>
<body>
<div></div>
<div class="wrapper">
<div class="show"></div>
</div>
<script>
//------------------当光标移入子元素show的橙色区域时,触发mouseenter事件
var odiv = document.getElementsByClassName('wrapper')[0];
var timer = null;
odiv.onmouseenter = function () {
startMove(odiv, 0)
};
//------------光标移开子元素show区域时,触发mouseleave事件
odiv.onmouseleave = function () {
startMove(odiv, -400)
};
//-----------------------------定义一个缓冲运动-----------------
function startMove(obj, target) {
clearInterval(timer);
var speed;
timer = setInterval(function () {
speed = (target - obj.offsetLeft) / 7;
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
if (obj.offsetLeft === target) {
clearInterval(timer);
} else {
obj.style.left = obj.offsetLeft + speed + 'px';
}
}, 30)
}
</script>
</body>
</html>
子区域show是橙色区域,父元素是wrapper区域,由于css中定义wrapper是负的position,所以父元素被隐藏了,我想要达成的效果是鼠标移到橙色区域后,事件冒泡到父区域wrapper,wrapper区域position改变做缓冲运动弹开。
可以我们可以惊奇的发现,在这种情况下,平时不能冒泡的mouseenter却冒泡了,如果再写一个子元素,在子元素的加个阻止冒泡事件,也不能停止show区域向其父元素wrapper区域冒泡的情况。
var show = document.getElementsByClassName('show')[0];
show.onmouseenter = function(){
return false;
}
如果不用mouseenter事件改用mouseover事件,在子元素加上阻止冒泡事件后,是可以停止show区域向其父元素wrapper区域冒泡的情况。
mouseenter这个事件是IE写的,在IE9以下版本这个是不能冒泡的,而我在IE9以上版本测试也发现跟刚才同样的问题,查找了相关资料发现并不能解决疑惑,个人认为这是一个小BUG,由于实在找不到原因,我认为最好还是写mouseover好一些。
当然如果有某位大佬知道原因的话希望能解答一下,不甚感谢!