繁体   English   中英

覆盖 !important 风格

[英]Overriding !important style

标题几乎总结了它。

外部样式表具有以下代码:

td.EvenRow a {
  display: none !important;
}

我试过使用:

element.style.display = "inline";

element.style.display = "inline !important";

但两者都不起作用。 是否可以使用 javascript 覆盖 !important 样式。

这是一个greasemonkey 扩展,如果这有区别的话。

您可以使用几个简单的单线来执行此操作。

  1. 在元素上设置“样式”属性

    element.setAttribute('style', 'display:inline !important');

或者...

  1. 修改style对象的cssText属性:

    element.style.cssText = 'display:inline !important';

要么会做这项工作。

===

我编写了一个名为“important”的 jQuery 插件来操作元素中的!important规则,: http : //github.com/premasagar/important

===

编辑:正如评论中所分享的,标准 CSSOM 接口(用于与 CSS 交互的 JavaScript 的 API)提供了setProperty方法:

element.style.setProperty(propertyName, value, priority);

例如:

document.body.style.setProperty('background-color', 'red', 'important');

element.style有一个setProperty方法,可以将优先级作为第三个参数:

element.style.setProperty("display", "inline", "important")

在旧 IE 中不起作用,但在当前浏览器中应该没问题

我相信唯一的方法是将样式添加为带有 '!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 后缀)将覆盖其他先前设置的样式。 如果您不使用后缀,请确保将“特殊性”等概念考虑在内。

您可以使用:

element.style.setProperty("display", "inline", "important");

https://developer.mozilla.org/zh-CN/docs/Web/API/CSSStyleDeclaration/setProperty

以@Premasagar 的出色回答为基础; 如果您不想删除所有其他内联样式,请使用此

//accepts the hyphenated versions (i.e. not 'cssFloat')
addStyle(element, property, value, important) {
    //remove previously defined property
    if (element.style.setProperty)
        element.style.setProperty(property, '');
    else
        element.style.setAttribute(property, '');

    //insert the new style with all the old rules
    element.setAttribute('style', element.style.cssText +
        property + ':' + value + ((important) ? ' !important' : '') + ';');
}

不能使用removeProperty()因为它不会删除 Chrome 中的!important规则。
不能使用element.style[property] = ''因为它在 FireFox 中只接受驼峰式大小写。

我刚刚发现的更好的方法:尝试比使用选择器的页面CSS更具体。 我今天只需要这样做,它就像一个魅力! W3C网站上的更多信息: http : //www.w3.org/TR/CSS2/cascade.html#specificity

如果要在 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 + ";";
  }
}

style.cssText支持所有主流浏览器

用例示例:

var elem = document.getElementById("elementId");
setCssTextStyle(elem, "margin-top", "10px !important");

这是演示的链接

如果您所做的只是向页面添加 css,那么我建议您使用 Stylish 插件,并编写用户样式而不是用户脚本,因为用户样式更有效和更合适。

请参阅此页面,了解有关如何创建用户样式的信息

https://developer.mozilla.org/en-US/docs/Web/CSS/initial

在 css3 中使用初始属性

 <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>

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)

如果你通过java脚本注入一个类(例如:'show'),而不是注入样式,它就会起作用。 但在这里你需要像下面这样的 css。 添加的 class css 规则应低于您的原始规则。

td.EvenRow a{
  display: none !important;
}

td.EvenRow a.show{
  display: block !important;
}

我们还有另一种可能从 CSS 中删除属性值。

就像在js中使用replace方法一样。 但是您必须确切地知道样式的 ID,或者您可以编写一个 for 循环来检测它(计算页面上的样式,然后检查这些“包含”或“匹配”中的任何一个是否为!important值。&您也可以计算 - 有多少包含它们,或者只是简单地编写一个全局 [regexp: /str/gi] 替换方法)

我的很简单,但是我附上了一个jsBin,例如:

https://jsbin.com/geqodeg/edit?html,css,js,output

首先,我在 CSS 中为 Yellow !important设置了正文背景,然后我用 JS 覆盖了 darkPink。

下面是一段代码,用于使用 jquery 设置样式属性的重要参数。

$.fn.setFixedStyle = function(styles){
    var s = $(this).attr("style");
    s = "{"+s.replace(/;/g,",").replace(/'|"/g,"");
    s = s.substring(0,s.length-1)+"}";
    s = s.replace(/,/g,"\",\"").replace(/{/g,"{\"").replace(/}/g,"\"}").replace(/:/g,"\":\"");
    var stOb = JSON.parse(s),st;
    if(!styles){
     $.each(stOb,function(k,v){
      stOb[k] +=" !important";
     });
    }
    else{
     $.each(styles,function(k,v){
      if(v.length>0){
        stOb[k] = v+" !important";
      }else{
        stOb[k] += " !important";  
      }
     });
    }
    var ns = JSON.stringify(stOb);
    $(this).attr("style",ns.replace(/"|{|}/g,"").replace(/,/g,";"));
};

用法非常简单。只需传递一个包含您要设置为重要的所有属性的对象。

$("#i1").setFixedStyle({"width":"50px","height":""});

还有两个附加选项。

1. 将重要参数添加到已经存在的样式属性中,传递空字符串。

2.为所有存在的属性添加重要参数,不要传递任何东西。 它会将所有属性设置为重要。

这是它的现场直播。 http://codepen.io/agaase/pen/nkvjr

暂无
暂无

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

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