javascript - js How to dynamically add the background color of li, and delete the same class of other sibling li
天蓬老师
天蓬老师 2017-05-19 10:38:06
0
2
634
<ul>
    <li><a href="#banner"><span class="list-nav"></span></a></li>
    <li><a href="#section-one"><span class="list-nav"></span></a></li>
    <li><a href="#section-two"><span class="list-nav"></span></a></li>
    <li><a href="#section-three"><span class="list-nav"></span></a></li>       
</ul>

$('.list-nav').first().addClass("spanList");
$('.list-nav').on('click',function(){
    $(this).css("background","#6090b6");
    $(this).addClass("spanList");
    $(this).siblings().removeClass("spanList");
    var href = $(this).attr("href");
    var pos = $(href).offset().top;
    $("html,body").animate({scrollTop: pos}, 1000);       
    return false;
})

I want to change the color of this when clicked, but other sibling li cancel the existing background color. And when other sibling elements are clicked, the sibling elements get the background color, and the background color of this is cancelled.

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(2)
左手右手慢动作

According to the idea of ​​​​your code, you just want to operate the span element and have no intention of operating li, so the code is implemented like this

$('.list-nav').first().addClass("spanList");
$('.list-nav').on('click',function(){
    $(this).css("background","#6090b6");
    $(this).addClass("spanList");
    
    /** 以下这段实现你说的功能 **/
    var $otherSpans = $(this).closest('li').siblings().find('span.list-nav');
    $otherSpans.css("background", "");
    $otherSpans.removeClass("spanList");
     /** 以上这段实现你说的功能 **/
    
    var href = $(this).attr("href");
    var pos = $(href).offset().top;
    $("html,body").animate({scrollTop: pos}, 1000);       
    return false;
})

Online Demo

过去多啦不再A梦

…$this.addClass("").closest("li").siblings("li").find("").removeAttr("")

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template