jQuery的class操作/一些方法

<!--@description-->
<!--@author beyondx-->
<!--@date Created in 2022/08/01/ 15:14-->
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>标题</title>
    <style>
        div {
            width: 100px;
            height: 100px;
            margin-top:10px;
        }
        .bgc {
            background-color: green;
        }
        .fontSize30 {
            font-size: 30px;
        }
        .width200 {
            width: 200px;
        }

    </style>
</head>
<body>
<input type="button" value="添加类" id="addClass"/>
<input type="button" value="移除类" id="removeClass"/>
<input type="button" value="判断类" id="hasClass"/>
<input type="button" value="切换类" id="toggleClass"/>
<div id="div1" class="bgc ">div1</div>
</body>
</html>

<script src="jquery-1.12.4.js"></script>
<script>
    $(function () {
        //1.添加类 addClass(类名);
        $('#addClass').click(function () {
            // 1.1. 给 id 为 div1 的元素 添加类
            // 添加 单个类
            // $('#div1').addClass('fontSize30');

            // 1.2. 添加 多个类
            $('#div1').addClass('fontSize30 width200');
        });

        //2.移除类
        $('#removeClass').click(function () {
            // 2.1.给 id为 div1的元素 移除类
            // $('#div1').removeClass('fontSize30');
            // 移除多个类
            // $('#div1').removeClass('fontSize30 width200');

            // 不写参数, class值, 全部移除
            $('#div1').removeClass();
        });

        //3.判断类
        $('#hasClass').click(function () {
            console.log($('#div1').hasClass("bgc"));
            console.log($('#div1').hasClass("fontSize30"));
            console.log($('#div1').hasClass("width200"));
        });


        //4.切换类
        $('#toggleClass').click(function () {
            // 如果元素 有某个类, 就移除这个类, 如果元素没有这个类, 就添加这个类
            $('#div1').toggleClass("fontSize30");
        });

    });
</script>

参考链接
https://api.jquery.com/addClass/
https://api.jquery.com/removeClass/
https://api.jquery.com/hasClass/
https://api.jquery.com/toggleClass/

posted on 2022-08-01 15:42  beyondx  阅读(73)  评论(0编辑  收藏  举报

导航