刚开始照着老师的代码一行行对照,发现js动画函数代码并没有问题,检查css发现了问题所在。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
body {
overflow: hidden;
}
.big {
position: relative;
left: 1520px;
top: 600px;
width: 350px;
height: 40px;
}
.yc {
position: absolute;
/* z-index: 2; */
top: 0;
left: 16px;
width: 100px;
height: 20px;
background-color: blue;
line-height: 20px;
text-align: center;
}
.cx {
position: relative;
display: inline-block;
z-index: 2;
height: 20px;
background-color: blue;
}
</style>
<script src="animate.js"></script>
</head>
<body>
<div class="big">
<span class="cx">←</span>
<div class="yc">看到我啦</div>
</div>
<script>
var cx = document.querySelector('.cx')
var yc = document.querySelector('.yc')
cx.addEventListener('mouseenter', function () {
animate(yc, -84)
})
cx.addEventListener('mouseleave', function () {
animate(yc, 16)
})
</script>
</body>
</html>
根据子绝父相,yc盒子设置了绝对定位,big父盒子设置了绝对定位。但是另一个子盒子cx并没有设置定位。问题的根源在于cx盒子没有设置一个比yc盒子更高的层级。而想要设置层级则必须得给cx盒子也添加定位。之前没有设置层级导致动画移过去时两盒子相撞,导致鬼畜。
function animate(obj, target, calback) {
// 为了防止开启多个定时器,每执行一次清楚一次定时器
clearInterval(obj.timer)
// 一个对象只用一个定时器,将定时器作为对象的属性
obj.timer = setInterval(function () {
// 变速运动需要一个变速的变量 setp为步长
var step = (target - obj.offsetLeft) / 10
// 考虑到step往回走为负值,有时需要向下取整,所以添加一个三元表达式
step = step > 0 ? Math.ceil(step) : Math.floor(step)
// 不能让定时器一直跑,设定一个结束条件
if (obj.offsetLeft == target) {
clearInterval(obj.timer)
if (calback) {
calback()
}
}
// 根本原理,左边距+1.有lef所以一定要进行定位
obj.style.left = obj.offsetLeft + step + 'px'
}, 15)
}
此处所用的动画代码。