首页 > 如何通过原生JS获取CSS文件中设置的值?

如何通过原生JS获取CSS文件中设置的值?

#photo {
  width: 270px;
  height: 270px;
  -webkit-transform: rotate(30deg);
}

我想要通过js获取到#photo上的transform属性值,请问如何获取?


如果是元素上的style定义的样式

div.style['stylename']

如果是要获取在css文件里定义或者在html里的用

getComputedStyle

有一只貘曾经给过我这样一个函数,用于获取某个元素的css样式。代码如下。

  1. 首先判断内联的属性 node.style.getPropertyValue;
  2. 然后使用 node.ownerDocument.defaultView.getMatchedCSSRules 获取应用在该元素上的 css 样式列表;

这段函数可以说是真正找到作用在页面元素上的 css 的原始值。

getComputedStyle 只是获取渲染结束后的最终样式。下面的 demo 可以展示貘大提供的函数和 getComputedStyle 获取的值的差别。

http://jsfiddle.net/NRP6H/1/

注意

该函数对静态资源分域处理的后的 css 无效。如 A 站的 css 放在 CDN 上,CDN 域名与 A 站不一致,则该函数无法获取到正确的值。


函数

/**
 * Returns specified style property information that is defined on specified
 * node (including inline style) by name.
 * @param {object} node node to get prototypes for.
 * @param {boolean} authorOnly Determines whether only author styles need to
 *     be added.
 * @param {string} propertyName CSS property name.
 * @return {object} value of specified style property information. Return
 *     null if the specified property is not defined on the node.
 */
// TODO: replace getDefinedStylePropertyByName with getSpecifiedStyleValue
// This name is too long and has useless authorOnly parameter.
function getDefinedStylePropertyByName(node, authorOnly, propertyName) {
  // CSSStyleDeclaration.getPropertyValue returns null instead of
  // empty string if the property has not been set in Webkit. So we
  // initialize the return value as null here.
  // http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration
  var value = null;
  if (!node || node.nodeType != Node.ELEMENT_NODE)
    return value;

  if (node.style) {
    value = node.style.getPropertyValue(propertyName);
    // The !important style takes precedence.
    if (node.style.getPropertyPriority(propertyName))
      return value;
  }

  var styleRules = node.ownerDocument.defaultView.getMatchedCSSRules(
    node, '', authorOnly);
  if (!styleRules)
    return value;

  for (var i = styleRules.length - 1; i >= 0; --i) {
    var style = styleRules[i].style;
    // The !important style may override inline style.
    if (style.getPropertyPriority(propertyName))
      return style.getPropertyValue(propertyName);
    if (!value)
      value = style.getPropertyValue(propertyName);
  }
  return value;
}

getComputedStyle(obj,null)['-webkit-transform']
>"matrix(0.8660254037844387, 0.49999999999999994, -0.49999999999999994, 0.8660254037844387, 0, 0)"
【热门文章】
【热门文章】