简体   繁体   中英

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

now is 2020, and my target is chrome only. I want to check it on chrome only, so it is not same question. 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'.

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. 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. After the browser rendered the dom, it's hard to find which rule has changed an specific element. The connection between element in dom and css rule is gone (in my opinion).

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

See: MDN getPropertyPriority

thank you @dandavis, i have change my idea. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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