首页 前端知识 html css js实现导航栏色块跟随滑动

html css js实现导航栏色块跟随滑动

2024-08-16 22:08:22 前端知识 前端哥 442 273 我要收藏

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>
复制

转载请注明出处或者链接地址:https://www.qianduange.cn//article/15866.html
标签
评论
还可以输入200
共0条数据,当前/页
发布的文章

安装Nodejs后,npm无法使用

2024-11-30 11:11:38

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!