jquery—addClass方法和removeClass方法

addClass ( ) : 给选中的元素添加class类名;

可以传class类名,也可以传function函数。

removeClass ( ) : 把选中的元素的class类名删除;

可以传class类名,也可以传function函数。

下边我们通过一个小例子理解下两个方法

需求是——有四个div,起始背景颜色都是黄色,被点击的div元素背景变绿;

效果是

方法一:把样式写在css中,我们预先把第一个div元素的背景颜色设置为绿颜色,当点击div的时候,先删除所有div中带有active的class类名,然后当前被点击的div添加上active类名,从而实现了被点击的div背景变绿,其他div颜色为黄色。

<style>
    .box{
        width:100px;
        height:100px;
        background-color:yellow;
        margin-bottom:5px;
        display: inline-block;
        color:#fff;
    }
    .box.active{
        background-color:green;
    }
</style>
<body>
    <div class="box active">1</div>
    <div class="box">2</div>
    <div class="box">3</div>
    <div class="box">4</div>
<script>
     // 方法一:
     $(".box").click(function(e){
         $(".box").removeClass("active");
         $(this).addClass("active");
     })
</script>

方法二:全部利用js来实现,思路也很简单,点击div时,先把所有div背景颜色设置为初始的黄色,然后被点击的div颜色背景颜色变为绿色。(但是此方法不推荐,首先从复用性来说,当一个页面有个多相似功能的时候,我们给元素添加一个类名即可,复用性高,从缓存机制来讲,当我们访问一个网页的时候,会从服务器拿到html css js 图片··· 等资源,浏览器会把css文件缓存到本地的,js则不会被缓存!)

// 方法二:
$(".box").click(function(e){
   $(".box").css({background:"yellow"})
   $(this).css({background:"green"})
})

方法三:跟方法一差不多,只不过更简化了一些:

思路是被点击的div添加类名active,其它的div移除active ;  silings()方法是选择与除自己之外所有同级的元素,后边小编会详解此方法。

// 方法三:
$(".box").click(function(e){
     $(this).addClass("active").siblings().removeClass("active");
})

hasClass:被选中的元素中是否有hasClass中的类名,有返回true,无返回false,返回的是布尔值;

       <div class="box active">1</div>
       <div class="box">2</div>
    <script>
       console.log( $(".box").hasClass("active") ) //true
       console.log( $(".box").hasClass("test") ) //false
    </script>

猜你喜欢

转载自blog.csdn.net/qq_42778001/article/details/90298893