样式操作

# 1. 通过style 属性

  • 可以获取修改元素的样式。
  • 低版本高版本浏览器均支持。

注意:

  • 仅仅能 获取修改 行内样式(也就是写在标签上的style属性中)
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <body>
    <div class="box1" style="width: 100px;height: 100px;"></div>
    <script type="text/javascript">
      let box1 = document.querySelector('.box1');
      console.log(box1.style.width); // 获取样式
      box1.style.width= '300px';  // 修改样式
      console.log(box1.style.width); 
    </script>
  </body>
</html>

# 2. window.getComputedStyle()

  • 此方法返回节点的样式对象(行内和外联样式),但是只是可读的,不能修改。

  • 仅兼容高版本浏览器

let style = window.getComputedStyle(element, [pseudoElt]);

// 参数一: 元素节点 element

// 指定为元素 , 一般为null  可选
      let box1 = document.querySelector('.box1');
      let styleObj = getComputedStyle(box1);   // 拿到样式对象
      console.log(styleObj.height);   // 读取高度
      console.log(styleObj.width);   // 读取宽度

      styleObj.height = "300px"; // 报错

此方法有兼容性的问题,在低版本浏览器下不兼容。

# 3.currentStyle属性 (兼容低版本浏览器)

  • 此方法返回节点的样式对象(行内和外联样式),但是只是可读的,不能修改。
  • 兼容IE低版本浏览器。
let box1 = document.querySelector('.box1');
let styleObj = window.currentStyle;
console.log(styleObj.height); // 读取高度

# 4. getBundingClientRect()

Element.getBoundingClientRect() 方法返回元素的大小及其相对于视口的位置 称之为高级用法(掌握)

rectObject = object.getBoundingClientRect();

// rectObject => left, top, right, bottom, x, y, width, 和 height

let styleRect = box1.getBoundingClientRect();
console.log(styleRect);
// bottom: 523.5
// height: 100
// left: 319
// right: 419
// top: 423.5
// width: 100
// x: 319
// y: 423.5
Last Updated: 1/17/2021, 11:11:54 PM