search

Home  >  Q&A  >  body text

javascript - js How to dynamically add the background color of li, and delete the same class of other sibling li

<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.

天蓬老师天蓬老师2746 days ago636

reply all(2)I'll reply

  • ringa_lee

    ringa_lee2017-05-19 10:40:06

    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

    reply
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-05-19 10:40:06

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

    reply
    0
  • Cancelreply