标题很好地概括了它。
外部样式表有以下代码:
td.EvenRow a {
display: none !important;
}
我试过使用:
element.style.display = "inline";
and
element.style.display = "inline !important";
但两者都不奏效。是否可以使用javascript重写!important样式?
这是一个油猴扩展,如果这使差异。
标题很好地概括了它。
外部样式表有以下代码:
td.EvenRow a {
display: none !important;
}
我试过使用:
element.style.display = "inline";
and
element.style.display = "inline !important";
但两者都不奏效。是否可以使用javascript重写!important样式?
这是一个油猴扩展,如果这使差异。
当前回答
而不是注入样式,如果你通过java脚本注入一个类(例如:'show'),它将工作。但这里你需要像下面这样的css。添加的类CSS规则应该在原始规则的下面。
td.EvenRow a{
display: none !important;
}
td.EvenRow a.show{
display: block !important;
}
其他回答
如果您所做的只是向页面添加css,那么我建议您使用Stylish插件,并编写用户样式而不是用户脚本,因为用户样式更有效和合适。
有关如何创建用户样式的信息,请参阅此页
您可以使用几个简单的一行程序来完成此任务。
在元素上设置一个"style"属性:
element.setAttribute('style', 'display:inline !important');
还是……
修改样式对象的cssText属性:
element.style.cssText = 'display:inline !important';
两者都可以。
===
我写了一个jQuery插件“important”来操作元素中的重要规则,:http://github.com/premasagar/important
===
编辑: 正如评论中所分享的,标准CSSOM接口(JavaScript与CSS交互的API)提供了setProperty方法:
element.style.setProperty(propertyName, value, priority);
E.g:
document.body.style.setProperty('background-color', 'red', 'important');
如果你想在DOM元素样式属性中更新/添加单个样式,你可以使用这个函数:
function setCssTextStyle(el, style, value) {
var result = el.style.cssText.match(new RegExp("(?:[;\\s]|^)(" +
style.replace("-", "\\-") + "\\s*:(.*?)(;|$))")),
idx;
if (result) {
idx = result.index + result[0].indexOf(result[1]);
el.style.cssText = el.style.cssText.substring(0, idx) +
style + ": " + value + ";" +
el.style.cssText.substring(idx + result[1].length);
} else {
el.style.cssText += " " + style + ": " + value + ";";
}
}
风格。所有主流浏览器都支持cssText。
用例示例:
var elem = document.getElementById("elementId");
setCssTextStyle(elem, "margin-top", "10px !important");
这里是演示的链接
https://developer.mozilla.org/en-US/docs/Web/CSS/initial
在css3中使用initial属性
<p style="color:red!important">
this text is red
<em style="color:initial">
this text is in the initial color (e.g. black)
</em>
this is red again
</p>
而不是注入样式,如果你通过java脚本注入一个类(例如:'show'),它将工作。但这里你需要像下面这样的css。添加的类CSS规则应该在原始规则的下面。
td.EvenRow a{
display: none !important;
}
td.EvenRow a.show{
display: block !important;
}