gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:08:40 24 4
gpt4 key购买 nike

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

<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顺便说一句。

最佳答案

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

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 函数和 matchesSelector所以在旧浏览器中没有垫片将无法工作。另外,您还可以按优先级等进行过滤——例如,您可以删除所有优先级低于内联样式的属性,等等。

关于javascript - 是否可以使用 Javascript 检查样式标签内是否定义了某些 CSS 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15667426/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com