js控制样式属性: className与classList

1.className 的作用: 获取或设置指定元素的 class 属性的值。

2.className 的特点:当使用className为标签赋值新类名时,旧类名会被覆盖

代码如下:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .yellow {
      width: 300px;
      height: 300px;
      background-color: skyblue;
    }

    .pink {
      width: 100px;
      height: 100px;
      background: pink;
      color: hotpink;
    }

    .green {
      color: green;
    }
  </style>
</head>

<body>
  <div class="box yellow">随便一些文本内容</div>
  <script>
    // 获取 DOM 节点
    const box = document.querySelector('.box')
    const div = document.querySelector('div')

    //输出box结点(标签)所拥有的类名
    document.write(box.className + '<br>')

    // 使用className将新类名赋值给标签,旧类名会被覆盖
    //即给box添加样式pink
    box.className = 'pink'

    //输出box结点(标签)所拥有的类名
    document.write(box.className)

    box.className = 'green' //即给box添加样式green
  </script>
</body>

</html>

因此为了解决className 容易覆盖以前的类名的问题,我们可以通过classList方式追加和删除类名

3、Element.classList 是一个只读属性,返回一个元素 class 属性的动态 DOMTokenList 集合。这可以用于操作 class 集合。

代码如下:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    div {
      width: 200px;
      height: 200px;
      background-color: pink;
    }

    .active {
      width: 300px;
      height: 300px;
      background-color: greenyellow;
      margin-left: 100px;
    }
  </style>
</head>

<body>

  <div class="gg one"></div>
  <script>
    // 1.获取元素
    let box = document.querySelector('div')

    // 2.使用 classList API 移除、添加类值

    // 原来:
    document.write('原来:' + box.className + '<br>')
    // remove() 移除 类
    box.classList.remove('one')
    document.write(box.className + '<br>')

    // add是个方法 添加  追加
    box.classList.add('active')
    document.write(box.className + '<br>')


    // 切换类(如果 one类值已存在,则移除它,否则添加它)
    let re = box.classList.toggle('one')
    document.write(box.className + '<br>')
    let re2 = box.classList.toggle('active')
    document.write(box.className + '<br>')


  </script>
</body>

</html>

  • 7
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值