我正在编写一个脚本,需要检查某些 CSS 属性是否在<style>
tag.
<style type="text/css">
#bar {width: 200px;}
</style>
<div id="foo" style="width: 200px;">foo</div>
<div id="bar">bar</div>
// 200px
console.log(document.getElementById("foo").style.width);
// an empty string
console.log(document.getElementById("bar").style.width);
if(property_width_defined_in_style_tag) {
// ...
}
这可能吗?
我并不是想得到getComputedStyle(ele).width
btw.
我不确定这是否是您想要的,它最接近您拥有元素实例的第一个伪代码,无论如何希望它有所帮助:
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));
}, []);
// get a reference to an element, then...
var bar = document.getElementById("bar");
// get only the css rules that matches that element
var elementRules = cssRules.filter(elementMatchCSSRule.bind(null, bar));
// check if the property "width" is in one of those rules
hasWidth = elementRules.some(propertyInCSSRule.bind(null, "width"));
我认为你可以为了你的目的重用所有这些代码,或者只是其中的一部分,它是有意模块化的——例如,一旦你拥有了所有的cssRules
压平,或者elementRules
,您仍然可以使用for
循环并检查您需要什么。
它使用 ES5 函数和匹配选择器所以在旧浏览器中如果没有垫片就无法工作。另外,您还可以按优先级等进行过滤 - 例如,您可以删除所有优先级低于内联样式属性的属性等。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)