你的浏览器不支持canvas

Enjoy life!

javascript - 获取样式 - style 和 getComputedStyle

Date: Author: JM

本文章采用 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议 进行许可。

一、 style对象

1.1 style

  • 任何支持 style 特性的 HTML 元素在 JavaScript 中都有一个对应的 style 属性。
  • 这个 style 对象是 CSSStyleDeclaration 的实例;
  • 包含着通过 HTMLstyle 特性指定的所有样式信息
  • 但不包含与外部样式表或嵌入样式表经层叠而来的样式。
  • 注意:由于 float 是 JavaScript 中的保留字,因此不能用作属性名。
    • “DOM2 级样式”规范规定样式对象上相应的属性名应该是 cssFloat;Firefox、Safari、Opera 和 Chrome 都支持这个属性
    • 而 IE 支持的则是 styleFloat

  • demo
  • 从下图你会发现:只有在行内设置的样式,width 值才会出现在 CSSStyleDeclaration
  • 而外部样式表或嵌入样式表经层叠而来的样式则不被包含!
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>style对象</title>
    <style>
        div {
            height: 100px;
            background: blue;
        }
    </style>
</head>
<div style="width: 100px;" id="div"></div>
<body>
<script>
    const div = document.getElementById('div')
    console.log(div.style)
</script>
</body>
</html>
  • style 对象

style

style

style

1.2 DOM 样式属性和方法

style

1.3 cssText

  • 通过 cssText 属性可以访问 style 特性中的 CSS 代码。
  • 在读取模式下,cssText 返回浏览器对 style 特性中 CSS 代码的内部表示。
  • 在写入模式下,赋给 cssText 的值会重写整个 style 特性的值;也就是 说,以前通过 style 特性指定的样式信息都将丢失。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>style对象 - cssText</title>
    <style>
        div {
            height: 100px;
            background: blue;
        }
    </style>
</head>
<div id="div"></div>
<body>
<script>
    const div = document.getElementById('div')
    div.style.width = `100px`
    console.log(div.style.cssText) // width: 100px;

    // 使用cssText修改样式
    div.style.cssText = `;width: 300px;`
    console.log(div.style.cssText) // width: 300px;

    // 不想被覆盖,可以这样写
    div.style.cssText += `; padding: 10px; margin: 40px;`
    console.log(div.style.cssText) // width: 300px; padding: 10px; margin: 40px;
</script>
</body>
</html>

1.4 length 和 item() 和 getPropertyValue()

  • 无论是使用方括号语法还是使用 item()方法,都可以取得 CSS 属性名(”background-color“, 不是”backgroundColor“)。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>style对象 - length 和 item() 和 getPropertyValue()</title>
</head>
<div style="width: 100px; height: 100px; background-color: blue" id="div"></div>
<body>
<script>
    const div = document.getElementById('div')
    const len = div.style.length
    console.log(len) // 3

    let cssAttr
    let value
    for (let i = 0; i < len; i++) {
      cssAttr = div.style[i]
      // 或者
      // cssAttr = div.style.item(i)
      value = div.style.getPropertyValue(cssAttr)
      console.log(`${cssAttr} = ${value}`)
    }
</script>
</body>
</html>

1.5 getPropertyCSSValue()

  • getPropertyCSSValue() 方法,它返回一个包含两个属性的 CSSValue 对象,这两个属性分别是:cssTextcssValueType
  • 其中,cssText 属性的值与 getPropertyValue() 返回的值相同,
  • cssValueType 属性则是一个数值常量,表示值的类型:
    • 0 表示继承的值,1 表示基本的值,2 表示值列表,3 表示自定义的值。

二、getComputedStyle()

  • getComputedStyle 是一个可以获取当前元素所有最终使用的CSS属性值。
  • 返回的是一个 CSS 样式声明对象([object CSSStyleDeclaration]),只读。
  • 语法如下:
// var style = window.getComputedStyle("元素", "伪类");

var dom = document.getElementById("test"),
style = window.getComputedStyle(dom , ":after");
  • 只是额外提示下:Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) 之前,第二个参数“伪类”是必需的(如果不是伪类,设置为null),不过现在嘛,不是必需参数了。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>getComputedStyle()</title>
    <style>
        div {
            height: 100px;
            background: blue;
        }
    </style>
</head>
<div style="width: 100px;" id="div"></div>
<body>
<script>
  const div = document.getElementById('div')
  const computedStyle = window.getComputedStyle(div, null)

  console.log(computedStyle.width) // 100px
  console.log(computedStyle.height) // 100px
  console.log(computedStyle.background) // rgb(0, 0, 255) none repeat scroll 0% 0% / auto padding-box border-box
</script>
</body>
</html>

2.2 兼容IE

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>getComputedStyle()</title>
    <style>
        div {
            height: 100px;
            background: blue;
        }
    </style>
</head>
<div style="width: 100px;" id="div"></div>
<body>
<script>
  const div = document.getElementById('div')
  const width = getEleComputedStyle(div, 'width')

  console.log(width) // 100px

  function getEleComputedStyle (ele, cName) {
    if (window.getComputedStyle) { // 非ie
      return window.getComputedStyle(ele, null)[cName]
    } else {
      return ele.currentStyle[cName] // ie
    }
  }
</script>
</body>
</html>

三、style 与 getComputedStyle() 的区别

  • 读写的问题:
    • ele.style:可读可写
    • window.getComputedStyle():只可读不可写
  • 获取对象的问题:
    • getComputedStyle 方法获取的是最终应用在元素上的所有 CSS 属性对象(即使没有CSS代码,也会把默认的祖宗八代都显示出来);
    • element.style 只能获取元素 style 属性中的 CSS 样式。
  • demo
const div = document.getElementById('div')
const width = getEleComputedStyle(div, 'width')
console.log(width) // 1350px
console.log(div.style.width) // 空白

对于本文内容有问题或建议的小伙伴,欢迎在文章底部留言交流讨论。