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

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

首先判断内联的属性 node.style.getPropertyValue;

然后使用 node.ownerDocument.defaultView.getMatchedCSSRules 获取应用在该元素上的 css 样式列表;

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

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

注意

该函数对静态资源分域处理的后的 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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值