标题很好地概括了它。
外部样式表有以下代码:
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样式?
这是一个油猴扩展,如果这使差异。
当前回答
您可以使用几个简单的一行程序来完成此任务。
在元素上设置一个"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');
其他回答
我相信做到这一点的唯一方法是添加样式作为一个新的CSS声明与'!重要”后缀。最简单的方法是在文档头添加一个新的<style>元素:
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('td.EvenRow a {display:inline !important;}')
使用上述方法添加的规则(如果使用!important后缀)将覆盖之前设置的其他样式。如果你不使用后缀,那么一定要考虑到“特异性”这样的概念。
https://jsfiddle.net/xk6Ut/256/
在JavaScript中覆盖CSS类的一个选项是为样式元素使用ID,这样我们就可以更新CSS类
function writeStyles(styleName, cssText) {
var styleElement = document.getElementById(styleName);
if (styleElement) document.getElementsByTagName('head')[0].removeChild(
styleElement);
styleElement = document.createElement('style');
styleElement.type = 'text/css';
styleElement.id = styleName;
styleElement.innerHTML = cssText;
document.getElementsByTagName('head')[0].appendChild(styleElement);
}
..
var cssText = '.testDIV{ height:' + height + 'px !important; }';
writeStyles('styles_js', cssText)
您可以使用几个简单的一行程序来完成此任务。
在元素上设置一个"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');
元素。style有一个setProperty方法,可以将优先级作为第三个参数:
element.style.setProperty("display", "inline", "important")
它在旧的ie中不起作用,但在当前的浏览器中应该没问题。
而不是注入样式,如果你通过java脚本注入一个类(例如:'show'),它将工作。但这里你需要像下面这样的css。添加的类CSS规则应该在原始规则的下面。
td.EvenRow a{
display: none !important;
}
td.EvenRow a.show{
display: block !important;
}