我无法使用"!important"规则注入样式

and*_*aby 46 javascript css firefox dom

我尝试使用以下代码注入样式:

document.body.style.color='green!important';
Run Code Online (Sandbox Code Playgroud)

根据CSS级联引用,通过应用!important规则,我可以胜过原点和特异性.

我尝试使用Firefox Firebug将其注入www.google.com,但没有运气.

如何使用!important规则注入前景色?

Bor*_*sky 98

根据规范,如果你想设置优先级,而不仅仅是值,你必须使用setProperty,如下所示:

document.body.style.setProperty ("color", "green", "important");
Run Code Online (Sandbox Code Playgroud)


Jay*_*ran 8

element.style.cssText = 'color:green !important';
Run Code Online (Sandbox Code Playgroud)

应该适合你.


Mar*_*lik 0

仅使用此:

document.body.style.color="green";
Run Code Online (Sandbox Code Playgroud)

您不必以这种方式使用 important 。无论如何,正如 Fatal 指出的那样,当 css 样式表中有直接重要的规则时,您需要覆盖它,这是行不通的。

这样,您必须动态创建样式表并将其添加到 head 中:

function addNewStyle(newStyle) {
   var styleElement = document.getElementById('styles_js');
   if (!styleElement) {
       styleElement = document.createElement('style');
       styleElement.type = 'text/css';
       styleElement.id = 'styles_js';
       document.getElementsByTagName('head')[0].appendChild(styleElement);
   }
   styleElement.appendChild(document.createTextNode(newStyle));
}
Run Code Online (Sandbox Code Playgroud)

然后你就可以像这样更新样式

addNewStyle('body {color:green !important;}')
Run Code Online (Sandbox Code Playgroud)