简体   繁体   English

我如何使用 javascript 检查 css 属性是否具有?在 chrome 中是否重要?

[英]How can i use javascript to check if a css property has !important in chrome?

now is 2020, and my target is chrome only.现在是 2020 年,我的目标只是 chrome。 I want to check it on chrome only, so it is not same question.我只想在 chrome 上检查它,所以这不是同一个问题。 and my final goal is to avoid an infinite observe loop.我的最终目标是避免无限观察循环。 this is my code:这是我的代码:

.bg-gray-light {
    background-color: #fafbfc!important;
}
var e=document.querySelector('div.pagehead.bg-gray-light');
var z= e.style.getPropertyPriority('background-color'); // here is ''
var t=getComputedStyle(e).getPropertyPriority('background-color'); //here is '' too.

So how do I judge whether the background-color is '.important'.那么如何判断背景颜色是否为'.important'。

FYI, I want to observe the style change and then change the style, but if it is,important.仅供参考,我想观察风格变化然后改变风格,但如果是的话,很重要。 i need to force the change by e.style.setProperty(), To avoid the infinite observe loop.我需要通过 e.style.setProperty() 强制更改,以避免无限观察循环。 i can not just try to change the style.我不能只是尝试改变风格。 So i need to know whether the background-color is '!important'.所以我需要知道背景颜色是否是'!重要'。

I'm afraid that the getPropertyPriority method works on stylesheet rules only.恐怕 getPropertyPriority 方法仅适用于样式表规则。 After the browser rendered the dom, it's hard to find which rule has changed an specific element.浏览器渲染 dom 后,很难找到哪个规则改变了特定元素。 The connection between element in dom and css rule is gone (in my opinion). dom 中的元素与 css 规则之间的联系消失了(在我看来)。

var declaration = document.styleSheets[0].cssRules[0].style;
var priority = declaration.getPropertyPriority("background-color");

See: MDN getPropertyPriority请参阅: MDN getPropertyPriority

thank you @dandavis, i have change my idea.谢谢@dandavis,我改变了主意。 i give up to check the ',important', i just try to change the style, but avoid infinite observe: like this:我放弃检查',重要',我只是尝试改变风格,但避免无限观察:像这样:

observer.disconnect();
            e.style.setProperty(
                property,
                rgbstring,
                priority, //'important' or ''
            );
regist(observer,document);

and above code is not enough to avoid infinite observer, so we need cheek the value is need to set, especially don't change it again and again.上面的代码不足以避免无限观察者,所以我们需要设置需要设置的值,特别是不要一次又一次地改变它。

thanks @dandavis谢谢@dandavis

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM