.nav {
width: 1000px;
height: 60px;
line-height: 60px;
margin: 0 auto;
position: relative;
}
ul {
width: 100%;
height: 100%;
padding: 0;
list-style: none;
}
ul li {
float: left;
width: 100px;
line-height: 60px;
text-align: center;
}
.cloud {
display: inline-block;
position: absolute;
width: 50px;
height: 30px;
background-color: pink;
left: 0;
}
ul li>a {
color: black;
text-decoration: none;
}
<div class="nav">
<span class="cloud"></span>
<ul>
<li class="current">首页</li>
<li><a href="#">团队力量</a></li>
<li><a href="#">企业文化</a></li>
<li><a href="#">成功案例</a></li>
<li><a href="#">招聘信息</a></li>
<li><a href="#">公司简介</a></li>
<li><a href="#">成功案例</a></li>
<li><a href="#">招聘信息</a></li>
<li><a href="#">公司简介</a></li>
</ul>
</div>
var cloud = document.querySelector('.cloud')
var nav = document.querySelector('.nav')
var lis = nav.querySelectorAll('li')
// console.log(cloud);
var current = 0;
for (var i = 0; i < lis.length; i++) {
lis[i].addEventListener('mouseenter', function () {
animate(cloud, this.offsetLeft)
})
// 鼠标离开
lis[i].addEventListener('mouseleave', function () {
animate(cloud, current)
})
// 鼠标点击
lis[i].addEventListener('click', function () {
current = this.offsetLeft;
})
}
function animate(obj, target, callback) {
clearInterval(obj.timer)
obj.timer = setInterval(function () {
// 把移动值改为整数避免存在小数
var step = (target - obj.offsetLeft) / 10;
step = step > 0 ? Math.ceil(step) : Math.floor(step);
if (obj.offsetLeft == target) {
clearInterval(obj.timer)
// 回调函数写在定时器结束后面
callback && callback();
}
// 把里面的移动值改为慢慢变小的值
obj.style.left = obj.offsetLeft + step + 'px'
}, 15)
}