【问题标题】:How can i use javascript to check if a css property has !important in chrome?我如何使用 javascript 检查 CSS 属性是否在 chrome 中具有 !important ?
【发布时间】:2020-09-08 11:50:39
【问题描述】:

现在是 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.

那么如何判断 background-color 是否为 '!important'。

仅供参考,我想观察样式变化然后更改样式,但如果它很重要,我需要通过 e.style.setProperty() 强制更改。 为了避免无限观察循环,我不能只是尝试改变风格。 所以我需要知道背景颜色是否是'!重要'。

【问题讨论】:

  • 这是否回答了您的问题,它包括除 getPropertyPriority 之外的完整功能吗? Check if css property has !important attribute applied
  • 我看了,但是我的目标是chrome,有没有更简单的解决方案?
  • 如果您手动设置#fafbfd而不是#fafbfc,我怀疑有人会注意到,但您可以轻松检测JS中的差异以防止无限循环。
  • @dandavis,因为修改失败,所以死循环,所以需要在js代码修改样式前检查一下。

标签: javascript css google-chrome dom cssom


【解决方案1】:

恐怕 getPropertyPriority 方法仅适用于样式表规则。 浏览器渲染 dom 后,很难找到哪个规则改变了特定元素。 dom 中的元素和 css 规则之间的联系已经消失(在我看来)。

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

见:MDN getPropertyPriority

【讨论】:

  • 它仅适用于在元素上设置的内联样式,不适用于我的代码,即由 css 类定义的样式。
  • 我错了,你的代码全是'背景色'?如何获得特殊元素的样式优先级?
  • 你能解释一下优先级是哪个元素吗?因为我只是得到 '' ,一个空字符串
【解决方案2】:

谢谢@dandavis,我改变了主意。我放弃检查'!重要',我只是尝试改变风格,但避免无限观察,像这样:

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

以上代码不足以避免无限观察者,所以我们需要厚颜无耻地设置需要设置的值,尤其是不要一次又一次地改变它。

感谢@dandavis

【讨论】:

    猜你喜欢
    • 2012-05-06
    • 2010-09-13
    • 1970-01-01
    • 2017-01-09
    • 2012-04-16
    • 2014-01-01
    • 2019-04-30
    • 2012-01-11
    相关资源
    最近更新 更多