jQuery类的操作相关方法

addClass:给指定元素添加类,如果添加多个,用空格隔开

removeClass:给指定元素删除类,如果删除多个,用空格隔开

toggleClass:切换类,如果有这个类就删除,没有就添加这个类

代码如下

<html>

<head>
<title></title>
</head>
    <style>
        .class1{
            width:100px;
            height:100px;
            background:red;
        }
        .class2{
            background:yellow;
        }
    </style>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script>
        
        $(function(){
            $('div').addClass('class1')      //添加class1
            $('div').removeClass('class1')   //删除class1
            //$('div').addClass('class1 class2')   //添加多个类
            //$('div').removeClass('class1 class2') //删除多个类
            $('div').toggleClass('class1')   //有class1这个类,就删除,没有就添加
        })
        
    </script>
    
<body>
    <div></div>
</body>
</html>

代码最终显示效果是class1这个类有,是通过$('div').toggleClass('class1') 添加的

猜你喜欢

转载自www.cnblogs.com/superCwen/p/9886273.html