JS classList追加,删除,切换类样式(add, remove , toggle)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        /* body{
            background: url("1.jpg") no-repeat top center/cover;
        } */
        .box{
            margin:0 auto;
            width:300px;
            height:300px;
            text-align: center;
            line-height: 300px;;
            font-size: 3em;
            color:red;
            border: 3px solid blue;
        }
        .addStyle{
            font-size: 1em;
            width:100px;
            height:100px;
            line-height:100px;
            background-color: #008c8c;
        }
    </style>
</head>
<body>
    <div class="box">
        文字
    </div>


    <script>
        // 获取元素
        const box = document.querySelector('.box');
        // 修改样式( 用classList类名不用加点)
        // 1.追加类样式
        box.classList.add('addStyle');
        // 2.删除类样式
        box.classList.remove('addStyle');
        // 3.切换类样式( 如果box盒子没有此类样式就追加,有就删除)
        box.classList.toggle('addStyle');// 追加了样式
        box.classList.toggle('addStyle');// 删除了样式
    </script>


    <!-- 获取随机数更换背景
    <script>
        // 取n~m的随机数方法
        function getRandom(n,m){
            return Math.floor(Math.random()*(m-n+1)+n);
        }
        // 随机数
        const random = getRandom(1,3);
            document.body.style.backgroundImage = `url(${random}.jpg)`;
    </script> -->
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值