如何在
JavaScript中检索已应用于元素的样式,不包括默认的用户代理样式(仅限内联样式表样式).
基本上,您可以在您最喜欢的开发人员工具的Computed选项卡中看到所有用户样式:
没有框架,IE8,Edge,Chrome和Firefox.
我期待答案是getComputedStyle减去getDefaultComputedStyle的结果,但是以跨浏览器的方式.看到所有开发人员工具都能够做到这一点,必须有一个解决方案:)
解决方法
有一个名为’styleSheets’的文档的只读属性.
var styleSheetList = document.styleSheets;
https://developer.mozilla.org/en-US/docs/Web/API/Document/styleSheets
通过使用此功能,您可以访问作者应用的所有样式.
这里有一个类似的问题但不重复,在这里:
Is it possible to check if certain CSS properties are defined inside the style tag with Javascript?
您可以从元素中获取应用的样式,使用我刚刚提到的问题的accepted answer排除默认用户代理样式.
那个答案没有提供元素自己的样式属性内容,所以我对代码进行了一些改进:
var proto = Element.prototype;
var slice = Function.call.bind(Array.prototype.slice);
var matches = Function.call.bind(proto.matchesSelector ||
proto.mozMatchesSelector || proto.webkitMatchesSelector ||
proto.msMatchesSelector || proto.oMatchesSelector);
// Returns true if a DOM Element matches a cssRule
var elementMatchCSSRule = function(element,cssRule) {
return matches(element,cssRule.selectorText);
};
// Returns true if a property is defined in a cssRule
var propertyInCSSRule = function(prop,cssRule) {
return prop in cssRule.style && cssRule.style[prop] !== "";
};
// Here we get the cssRules across all the stylesheets in one array
var cssRules = slice(document.styleSheets).reduce(function(rules,styleSheet) {
return rules.concat(slice(styleSheet.cssRules));
},[]);
var getAppliedCss = function(elm) {
// get only the css rules that matches that element
var elementRules = cssRules.filter(elementMatchCSSRule.bind(null,elm));
var rules =[];
if(elementRules.length) {
for(i = 0; i < elementRules.length; i++) {
var e = elementRules[i];
rules.push({
order:i,text:e.csstext
})
}
}
if(elm.getAttribute('style')) {
rules.push({
order:elementRules.length,text:elm.getAttribute('style')
})
}
return rules;
}
function showStyle(){
var styleSheetList = document.styleSheets;
// get a reference to an element,then...
var div1 = document.getElementById("div1");
var rules = getAppliedCss(div1);
var str = '';
for(i = 0; i < rules.length; i++) {
var r = rules[i];
str += '<br/>Style Order: ' + r.order + ' | Style Text: ' + r.text;
}
document.getElementById("p1").innerHTML = str;
}
#div1 {
float:left;
width:100px;
}
div {
text-align:center;
}
<div id="div1" style="font-size:14px;"> Lorem ipsum </div> <br/> <br/> <a href="javascript:;" onclick="showStyle()"> Show me the style. </a> <p id="p1"><p>