文章目录
- 一、效果展示
- 二、实现步骤
- 1.html
- 2.css
- 3.js
一、效果展示:
二、实现步骤
1.html
代码如下(示例):
<div class="navcontainer">
<nav class="navbox">
<li class="nav-items" id="moren">热门</li>
<li class="nav-items">同城</li>
<li class="nav-items">榜单</li>
<li class="nav-items">明星</li>
<li class="nav-items">搞笑</li>
<li class="nav-items">情感</li>
<li class="nav-items">周末</li>
<img src="列表.png" title="更多">
</nav>
</div>
2.css
代码如下(示例):
<style>
body{
background-color: #f1f2f5;
}
.navcontainer{
background-color: #fff;
width: 660px;
height: 50px;
margin: 0 auto;
display: flex;
align-items: center;
border-radius: 5px;
}
.navbox{
list-style: none;
width: 700px;
height: 30px;
border-radius: 4px;
}
.navbox li{
float: left;
margin-left: 5px;
line-height: 30px;
cursor: pointer;
width: 80px;
height: 30px;
text-align: center;
}
.navbox li:hover{
background-color:#fff2e5;
border-radius: 20px;
color: #ff8c14;
}
.active{
color: #ff8c14;
}
#moren{
color: #ff8c14;
}
img{
width: 20px;
height: 20px;
margin-top: 7px;
margin-left: 20px;
cursor: pointer;
}
</style>
2.js
代码如下(
<script>
//获取导航栏元素列表
var navItems = document.getElementsByClassName("nav-items");
//为每一个元素添加监听事件
for(var i =0;i<navItems.length;i++){
//移除所有元素的类名
navItems[i].addEventListener("click",function(){
for(var j=0;j<navItems.length;j++){
navItems[j].classList.remove('active');
navItems[j].removeAttribute("id");
}
//给当前点击的导航栏元素添加颜色
this.classList.add('active');
});
}
</script>