【JavaScript】45_间接修改css样式

16、间接修改css样式

除了直接修改样式外,也可以通过修改class属性来间接的修改样式

通过class修改样式的好处:

  1. 可以一次性修改多个样式
  2. 对JS和CSS进行解耦

元素.classList

是一个对象,对象中提供了对当前元素的类的各种操作方法

元素.classList.add() :向元素中添加一个或多个class

元素.classList.remove(): 移除元素中的一个或多个class

元素.classList.toggle() :切换元素中的class

元素.classList.replace(): 替换class

元素.classList.contains() :检查class

     <style>
         .box1 {
             width: 200px;
             height: 200px;
             background-color: #bfa;
         }
 ​
 ​
         .box2{
             background-color: yellow;
             width: 300px;
             height: 500px;
             border: 10px greenyellow solid;
         }
     </style>
 </head>
 <body>
     <button id="btn">点我一下</button>
     <hr>
     <div class="box1 box3 box4"></div><script>
         //点击按钮后,修改box1的宽度
         const btn = document.getElementById("btn")
         const box1 = document.querySelector(".box1")
 ​
         btn.onclick = function(){
             //除了直接修改样式外,也可以通过修改class属性来间接的修改样式
             // box1.className += 'box2'// box1.classList.add('box2','box3','box4')
             // box1.classList.add('box1')// box1.classList.remove('box2')
             box1.classList.toggle('box2')
             // box1.classList.replace('box2')let result = box1.classList.contains('box3')
             console.log(result)
         }
     </script>
 </body>
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

名之以父

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值