猿问

js 怎么动态添加li的背景颜色,其余同级li的同一个class删除

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

})

我想点击的时候将this改颜色,但是其他同级li取消已有的背景颜色。并且当点击其他同级元素时,同级元素获得背景颜色,this的背景颜色取消。

智慧大石
浏览 1031回答 1
1回答

茅侃侃

根据你的代码反应的思路,你只是想操作span元素,并没有操作li的意图,所以代码这样实现$('.list-nav').first().addClass("spanList");$('.list-nav').on('click',function(){&nbsp; &nbsp; $(this).css("background","#6090b6");&nbsp; &nbsp; $(this).addClass("spanList");&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; /** 以下这段实现你说的功能 **/&nbsp; &nbsp; var $otherSpans = $(this).closest('li').siblings().find('span.list-nav');&nbsp; &nbsp; $otherSpans.css("background", "");&nbsp; &nbsp; $otherSpans.removeClass("spanList");&nbsp; &nbsp; &nbsp;/** 以上这段实现你说的功能 **/&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; var href = $(this).attr("href");&nbsp; &nbsp; var pos = $(href).offset().top;&nbsp; &nbsp; $("html,body").animate({scrollTop: pos}, 1000);&nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; return false;})在线 Demo
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答