如何使用jQuery向元素中添加和删除多个class类?

2019-07-08 13:42:00 3427 1 编辑:深正互联 来源:互联网

给定一个HTML元素,如何使用JQuery从其中添加和删除多个class类?下面小编就来给大家介绍一下使用jQuery向元素中添加和删除多个class的方法,希望对大家有所帮助。


想要使用jQuery向HTML元素中添加和删除多个class类,首先使用jQuery选择器选择要添加多个class类的元素,然后使用addClass()方法向元素添加多个类,使用removeClass()方法删除多个类。

网站建设

addClass()方法用于向被选元素添加一个或多个类;该方法不会移除已存在的 class 属性,仅仅添加一个或多个 class 属性。


removeClass()方法从被选元素移除一个或多个类;如果没有规定参数,则该方法将从被选元素中删除所有类。


示例1:使用addClass()方法将两个类color和fontWeight添加到所选元素中


<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<title>如何添加多个类</title>

<style> 

            .color { 

                color: red; 

            } 

            .fontWeight { 

                font-weight: bold; 

            } 

        </style>

</head>

<body style = "text-align:center;">  

        <p id = "UP" style = "font-size: 19px;">单击按钮向元素添加多个类</p> 

        <button onClick = "Fun()">单击 </button> 

        <p id = "DOWN" style="color: green; font-size: 24px; font-weight: bold;"></p> 

        <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> 

        <script> 

            function Fun() { 

                $("#UP").addClass("color fontWeight"); 

                $('#DOWN').text("添加了两个类color和fontweight"); 

            } 

        </script>  

    </body>  

</html>

效果图:


1.gif


示例2:使用removeClass()方法从所选元素中删除两个类color和fontWeight


<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<title>如何删除多个类</title>

<style> 

            .color { 

                color: red; 

            } 

            .fontWeight { 

                font-weight: bold; 

            } 

        </style>

</head>


<body style = "text-align:center;">  

        <p id = "UP" class="color fontWeight" style = "font-size: 19px;">单击按钮向元素添加多个类</p> 

        <button onClick = "Fun()">单击 </button> 

        <p id = "DOWN" style="color: green; font-size: 24px; font-weight: bold;"></p> 

        <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> 

        <script> 

            function Fun() { 

                $("#UP").removeClass("color fontWeight"); 

                $('#DOWN').text("删除两个类color和fontweight"); 

            } 

        </script>  

    </body>  

</html>

效果图:


2.gif


以上就是如何使用jQuery向元素中添加和删除多个class类的详细内容


本站文章均为深正网站建设摘自权威资料,书籍,或网络原创文章,如有版权纠纷或者违规问题,请即刻联系我们删除,我们欢迎您分享,引用和转载,但谢绝直接搬砖和抄袭!感谢...
关注深正互联

15

技术从业经验

多一份方案,会有收获...

联系深正互联,免费获得专属《策划方案》及报价

在线咨询
微信交谈
拒绝骚扰,我们只想为给您带来一些惊喜...
多一份免费策划方案,总有益处。

请直接添加技术总监微信联系咨询

深正互联微信
扫描即可沟通