我尝试使用此代码注入样式:
document.body.style.color='green!important';
根据the CSS cascade ref,通过应用!important
规则,我可以胜过原点和特异性。
我尝试使用Firefox Firebug将其注入www.google.com,但没有运气。
如何使用!important
规则注入前景色?
答案 0 :(得分:97)
根据规范,如果要设置优先级而不仅仅是值,则必须使用setProperty
,如下所示:
document.body.style.setProperty ("color", "green", "important");
答案 1 :(得分:8)
element.style.cssText = 'color:green !important';
应该适合你。
答案 2 :(得分:2)
所有答案都很棒,但他们都认为该属性的value
为fixed
,如果不是
看看我的解决方案
this.style.setProperty("color", $(this).css('color'), "important");
而不是hand writing
值,我使用jquery $(this).css('attr')
答案 3 :(得分:1)
仅使用此:
document.body.style.color="green";
你不能以这种方式使用重要的东西。无论如何,Fatal指出,当你需要覆盖css样式表中有直接重要的规则时,这是行不通的。
通过这种方式,您必须动态创建样式表并将其广告在头部内:
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));
}
然后你可以像那样更新样式
addNewStyle('body {color:green !important;}')
答案 4 :(得分:1)
我想提一下,由于代码中的任何错误(除了空格),它可能不会起作用,但更多因为修改body标签不是一个特定的元素,类,或者你有什么创造所需的效果。
例如,搜索结果的页面文本具有“st”类。
所有搜索结果都封装在一个
<li>
标签。
所以这些效果的代码可能如下所示:
var arr = document.getElementsByClassName('st');
for(i=0; i<arr.length; i++){
arr[i].style.color="green";
}
答案 5 :(得分:1)
style.cssText是添加!important的唯一方法。
<script>
document.body.style.cssText='color: red !important;'
</script>
答案 6 :(得分:-1)
我需要保持!important对于以下代码的操作方法
<script> var size = $(window).width();
if(size >="1900" && size <="2890"){
$(document).ready(function(){ $(".myMove").click(function(){ $(".hqnblogo").animate({ left:'-22% ', top: '67%', height:'7%', }); $(".hqnbnaturalslogo").animate({ left: '86%', top: '20px', height:'7%', }); }); }); } </script>?