jQuery實現導航欄的樣式切換
樣式:
ul{ margin: 0 auto; height: 50px; background-color: #369; } ul>li{ text-decoration: none; display: inline-block; height: 50px; line-height: 50px; color: #fff; padding: 0 15px; border-left: 1px solid #365; } .active,ul>li:hover{ background-color: #fff; color: #369; cursor: pointer; }
html部分:
<ul>
<li>首頁</li><li>關於我們</li><li>產品中心</li><li>新聞中心</li><li>關於我們</li>
</ul>
方法一:
$li = $('ul>li'); // console.log($li); $li.bind('click',function(){ $this=$(this); $this.addClass('active'); $this.siblings().removeClass('active'); console.log('111'); });
方法二:(原生Js)
for(let i = 0 ;i < navs.length; i++){
navs[i].onclick = function(e){
let activedNav = this.parentNode.querySelector('.active');
if(activedNav == this){
return;
}
activedNav.className = '';
this.className = 'active';
}
}