![](https://i-blog.csdnimg.cn/blog_migrate/054760038390c260b5bb23e619a6cf23.png)
css样式
<style>
* {
margin: 0px;
padding: 0px;
}
ul {
list-style: none;
}
html,
body {
height: 100%;
width: 100%;
background: black;
}
a {
text-decoration: none;
}
ul {
position: relative;
background: #fff;
overflow: hidden;
width: 900px;
margin: 50px auto;
padding: 20px 0px;
display: flex;
border-radius: 5px;
}
ul li {
position: relative;
z-index: 10;
flex: 1;
text-align: center;
}
ul li a {
font-size: 18px;
color: #333;
}
.bg {
width: 83px;
height: 42px;
display: inline-block;
background-color: red;
position: absolute;
left: 34px;
top: 0px;
bottom: 0px;
margin: auto;
z-index: 2;
}
</style>
body
<body>
<ul>
<span class="bg"></span>
<li>
<a href="javascript:;">首页</a>
</li>
<li>
<a href="javascript:;">电视剧</a>
</li>
<li>
<a href="javascript:;">新电影</a>
</li>
<li>
<a href="javascript:;">新闻</a>
</li>
<li>
<a href="javascript:;">娱乐</a>
</li>
<li>
<a href="javascript:;">军事</a>
</li>
</ul>
<script>
// 需求:鼠标经过哪个导航栏目,背景色滑动过去
var liList = document.getElementsByTagName('li');
var bg = document.getElementsByClassName('bg')[0];
var header = 34;
var liLeft = 34;
console.log(34);
// 添加事件
// 遍历li
for (var i = 0; i < liList.length; i++) {
liList[i].onmouseover = function () {
liLeft = this.offsetLeft + (this.offsetWidth - bg.offsetWidth) / 2;
}
}
// 使用定时器
setInterval(function () {
header = header + (liLeft - header) / 10;
bg.style.left = header + 'px';
}, 10)
</script>
</body>