mouseenter 和mouseover的区别
- 当鼠标移动到元素上时就会触发mouseenter 事件
- 类似 mouseover,它们两者之间的差别是
- mouseover 鼠标经过自身盒子会触发,经过子盒子还会触发。mouseenter 只会经过自身盒子触发
- 之所以这样,就是因为mouseenter不会冒泡
- 跟mouseenter搭配鼠标离开 mouseleave 同样不会冒泡
Mouseover mouseout
和mouseenter mouseleave
代码示例:
mouseover:
father.addEventListener('mouseover', function(e) {
console.log('鼠标移入了父盒子');
})
son.addEventListener('mouseover', function(e) {
console.log('鼠标移入了子盒子');
})
鼠标移入子盒子还是会触发移入父盒子的函数
mouseenter:
father.addEventListener('mouseenter', function(e) {
console.log('鼠标移入了父盒子');
})
son.addEventListener('mouseenter', function(e) {
console.log('鼠标移入了子盒子');
})
没有事件冒泡
动画函数封装
动画实现原理:
通过定时器 setInterval() 不断移动盒子位置。
-
获得盒子当前位置
-
让盒子在当前位置加上1个移动距离
-
利用定时器不断重复这个操作
-
加一个结束定时器的条件
-
注意此元素需要添加定位,才能使用element.style.left
代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.father {
position: absolute;
width: 300px;
height: 300px;
background-color: blueviolet;
}
.son {
width: 150px;
height: 150px;
background-color: brown;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
<script>
let father = document.querySelector('.father');
function animate(obj, target) {
// 封装一个动画函数 参数1 为元素对象 (操作哪个元素) 参数2 为停止动画的条件
// 避免定时器的bug 使用之前先清除
clearInterval(obj.timer);
// 设置定时器
obj.timer = setInterval(function() {
// 如果满足了停止动画的条件就清除定时器 本质就是停止定时器
if (obj.offsetLeft >= target) {
clearInterval(obj.timer);
}
// 没30毫秒 元素的left加1像素
obj.style.left = obj.offsetLeft + 1 + 'px';
}, 30)
}
// 执行函数 传入元素和停止动画的条件
animate(father, 500);
</script>
</body>
</html>