JavaScript--currentStyle和getComputedStyle()的区别和联系

JavaScript中的currentStyle和getComputedStyle()都是用于获取元素的计算样式属性的方法,但它们适用于不同的情况。下面会对它们进行解释:

1.currentStyle:该属性是IE浏览器特有的,并且仅能在IE浏览器中使用。它用于获取指定元素的当前样式,返回的是一个样式属性对象。
示例用法: 

const element = document.getElementById('myElement');
const currentStyle = element.currentStyle;

// 获取背景颜色
const backgroundColor = currentStyle.backgroundColor;
console.log(backgroundColor);

2.getComputedStyle():该方法可以获取指定元素的计算样式,适用于大多数现代浏览器(包括Chrome、Firefox、Safari等)。它返回的也是一个样式属性对象。 
示例用法: 

const element = document.getElementById('myElement');
const computedStyle = window.getComputedStyle(element);

// 获取背景颜色
const backgroundColor = computedStyle.backgroundColor;
console.log(backgroundColor);

 需要注意的是,无论是currentStyle还是getComputedStyle()返回的样式值都是字符串形式,如果需要获取具体的数值,可以使用相关的方法进行转换(例如parseInt())。

因此,我们可以写一个适配各个浏览器的读取元素样式的方法。

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>适配浏览器的元素样式读取方法</title>
  <style>
    .example {
      width: 200px;
      height: 100px;
      background-color: red;
      color: white;
      font-size: 20px;
      padding: 10px;
      margin: 20px;
    }
  </style>
  <script>
    // 元素样式读取方法
    function getElementStyle(element, styleProperty) {
      if (element.currentStyle) { // IE浏览器
        return element.currentStyle[styleProperty];
      } else if (window.getComputedStyle) { // 标准浏览器
        return window.getComputedStyle(element)[styleProperty];
      }
    }

    // 示例用法
    window.onload = function() {
      var exampleElement = document.getElementById('example');
      var width = getElementStyle(exampleElement, 'width');
      var fontSize = getElementStyle(exampleElement, 'fontSize');

      console.log("宽度: " + width);
      console.log("字体大小: " + fontSize);
    };
  </script>
</head>
<body>
  <div id="example" class="example">示例元素</div>
</body>
</html>

在这个示例中,我们定义了一个名为getElementStyle的函数。该函数接受两个参数:element代表要获取样式的元素,styleProperty代表要获取的样式属性。
getElementStyle函数首先判断浏览器是否支持currentStyle属性,如果支持,则使用element.currentStyle[styleProperty]来获取元素的样式值。
如果浏览器不支持currentStyle属性,则判断是否支持getComputedStyle方法,如果支持,则使用window.getComputedStyle(element)[styleProperty]来获取元素的样式值。
在示例代码中,我们使用了getElementStyle函数来获取示例元素的宽度和字体大小,并将结果打印到控制台上。你可以根据需要修改和扩展这个示例来适应不同的浏览器和样式属性。

猜你喜欢

转载自blog.csdn.net/m0_74293254/article/details/131676305