分享一个小案例,使用原生 js 实现菜单点击动态添加 active类,没有使用jQuery。
样式:style.css
*{
margin: 0;
padding: 0;
}
ul{
margin: 0 auto;
display: flex;
justify-content: center;
align-items: center;
height: 50px;
list-style: none;
box-shadow: 0 2px 4px #eeeeee;
}
ul > li {
padding: 6px 16px;
margin: 0 5px;
border-right: 1px solid #f7f7f7;
border-bottom: 1px solid transparent;
cursor: pointer;
}
ul > li:last-child{
border-right: none;
}
li:hover, li:focus, .active {
color: #ff6615;
border-bottom: 1px solid #ff6615;
}
页面:index.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>原生js实现菜单动态添加active类</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<ul id="nav">
<li class="active">首页</li>
<li>产品中心</li>
<li>新闻资讯</li>
<li>文档下载</li>
<li>联系我们</li>
</ul>
<script>
function removeActiveClass(node) {
node.className = '';
}
let menus = document.querySelectorAll('#nav');
menus.forEach(function (value, index) {
value.addEventListener('click', function (e) {
var target = e.target;
Array.prototype.forEach.call(document.querySelectorAll('#nav li'), removeActiveClass);
target.className = 'active';
})
});
</script>
</body>
</html>
代码效果:
THE END !