No.36 JavaScript---CSS操作(JS操作CSS)

 

  • JS操作CSS样式,JS操作HTML中的元素。三者联动起来。
  • JS操作CSS样式有三种方式:
    • 通过HTML元素的style属性;
    • 通过元素节点的style属性;
    • 通过cssText属性。

1.1 HTML元素的style属性

  • 操作 CSS 样式最简单的方法,就是使用网页元素节点的 setAttribute 方法直接操作网页元素的 stye 属性。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div class = "box" id="box">我是一个块</div>
    <script>
        var box = document.getElementById("box")
        box.setAttribute("style","width:200px;height:200px;background:red")
    </script>

</body>
</html>

  "width:200px;height:200px;background:red" 这一串内容要一个一个字母敲,不太方便

1.2 元素节点的style属性

<body>
    <div class = "box" id="box">我是一个块</div>
    <script>
        var box = document.getElementById("box")
        box.setAttribute("style","width:200px;height:200px;background:red")

        box.style.width = "200px"; //等价于上面的一行代码
        box.style.height = "200px";
        box.style.background = "red";

    </script>

</body>
</html>

  

1.3 cssText属性

<body>
    <div class = "box" id="box">我是一个块</div>
    <script>
        var box = document.getElementById("box")
        box.setAttribute("style","width:200px;height:200px;background:red") //方式1

        box.style.width = "200px";//方式2
        box.style.height = "200px";
        box.style.background = "red";

        box.style.cssText = "width:200px;height:200px;background:red" // 方式3

    </script>

</body>

  三种方法一样的。一般第二种推荐,比较清晰

 

posted @ 2025-03-06 16:20  百里屠苏top  阅读(26)  评论(0)    收藏  举报