是否可以使用Javascript检查样式标记内是否定义了某些CSS属性?

use*_*156 3 javascript css styles

我正在编写一个脚本,需要检查<style>标签内是否定义了某些CSS属性.

<style type="text/css">
#bar {width: 200px;}
</style>
Run Code Online (Sandbox Code Playgroud)
<div id="foo" style="width: 200px;">foo</div>
<div id="bar">bar</div>
Run Code Online (Sandbox Code Playgroud)
// 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) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

这可能吗?

我不是想要getComputedStyle(ele).width顺便说一下.

Den*_*ret 5

你可以在javascript中完全探索styleSheets.

document.styleSheets数组开始.值是文档使用的不同样式元素或CSS文件.


ZER*_*ER0 5

我不确定这是你想要的,它最接近你的第一个伪代码,你有一个元素实例,无论如何希望它有帮助:

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"));
Run Code Online (Sandbox Code Playgroud)

我想你可以重用所有这些代码对你的目的,或者只是一些片断它,这是故意的模块化-例如,当你把所有的cssRules扁平化,或者elementRules,你仍然可以使用一个for循环,并检查你所需要的.它使用ES5函数和matchesSelector,因此在没有填充程序的旧浏览器中将无法运行.另外,您还可以按优先级等过滤 - 例如,您可以删除所有属性的优先级低于内联样式的属性等.