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

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

image

想要使用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类?

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容