简体   繁体   English

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

[英]I'm unable to inject a style with an “!important” rule

I tried to inject a style using this code: 我尝试使用以下代码注入样式:

document.body.style.color='green!important';

Per the CSS cascade ref , by applying the !important rule I can trump origin and specificity. 根据CSS级联引用 ,通过应用!important规则,我可以胜过原点和特异性。

I tried to inject this using Firefox Firebug into www.google.com however no luck. 我尝试使用Firefox Firebug将其注入www.google.com,但没有运气。

How do I inject a foreground color with an !important rule? 如何使用!important规则注入前景色?

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

document.body.style.setProperty ("color", "green", "important");
element.style.cssText = 'color:green !important';

应该适合你。

all answers are great but they all assumed the value of the attribute is fixed ,, what if not 所有的答案都很棒,但他们都认为属性的valuefixed ,如果没有的话

take look at my solution 看看我的解决方案

this.style.setProperty("color", $(this).css('color'), "important");

instead of hand writing the value, I got it using jquery $(this).css('attr') 而不是hand writing值,我得到它使用jquery $(this).css('attr')

style.cssText is the only way to add !important. style.cssText是添加!important的唯一方法。

<script>
   document.body.style.cssText='color: red !important;'
</script>

Use only this: 仅使用此:

document.body.style.color="green";

you can not have to use important in this way. 你不能以这种方式使用重要的东西。 Anyway as Fatal pointed out, this will not work, when there is directly important rule in css stylesheet, that you need to override. 无论如何,Fatal指出,当css样式表中存在直接重要的规则时,这将无法工作,您需要覆盖。

In that way, you have to dynamicaly create stylesheet and ad it inside 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));
}

Then you can update style just like that 然后你可以像这样更新样式

addNewStyle('body {color:green !important;}')

I would like to pose that it may not be working not so much due to any error in code (excepting the space) but more because modifying the body tag isn't a specific enough element, class, or what have you to create the desired effect. 我想提一下,由于代码中的任何错误(除了空间),它可能没有那么多工作,但更多的是因为修改body标签不是一个特定的元素,类,或者你有什么创建所需的影响。

Like for instance the page text of a search result has a class of "st". 例如,搜索结果的页面文本具有“st”类。 all search results are each encapsulated in an <li> tag. 所有搜索结果都封装在<li>标签中。

So some code to such effect might look like this: 所以这些效果的代码可能如下所示:

var arr = document.getElementsByClassName('st');
for(i=0; i<arr.length; i++){
    arr[i].style.color="green";
}

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

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