分享一個小案例,使用原生 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 !