我如何使用javascript检查CSS样式对!chrome重要!

问题描述 投票:1回答:1

现在是2020年,我的目标仅在chrome中,我只想在chrome上进行检查,因此不是同一问题。我的最终目标是避免无限观察循环。这是我的代码:

.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.

所以如何判断背景色是否为'!important'。

fyi,我想观察样式更改,而不是更改样式,但是,如果它很重要,我需要通过e.style.setProperty()强制更改它。为了避免无限观察循环,我不能只是尝试更改样式。所以我需要知道背景色是否为'!important'。

javascript css google-chrome dom cssom
1个回答
1
投票

恐怕getPropertyPriority方法仅适用于样式表规则。浏览器渲染了dom之后,很难找到哪个规则更改了特定元素。 dom中的元素与CSS规则之间的联系消失了(我认为)。

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

参见:MDN getPropertyPriority

© www.soinside.com 2019 - 2024. All rights reserved.