【问题标题】:Overriding !important style覆盖 !important 风格
【发布时间】:2010-10-02 12:42:27
【问题描述】:

标题几乎概括了它。

外部样式表有如下代码:

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

我尝试过使用:

element.style.display = "inline";

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

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

这是一个greasemonkey扩展,如果有影响的话。

【问题讨论】:

    标签: javascript css


    【解决方案1】:

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

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

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

    或者...

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

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

    两者都能胜任。

    ===

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

    ===

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

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

    例如:

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

    【讨论】:

    • 我认为使用cssText比添加style标签更简单。
    • @Guss - 我给出的第一个例子是style 属性,而不是标签/元素。
    • 是的,我知道-我将您的答案与@J-P 选择的答案进行了比较,我想说我认为您的答案更好。
    • 为了防止覆盖其他属性,你想使用element.style.cssText += ';display:inline !important;';
    • @user123444555621,Premasagar。不妨使用更好的选择:element.style.setProperty.
    【解决方案2】:

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

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

    didn't work in old IEs 但在当前浏览器中应该没问题。

    【讨论】:

    • 最佳解决方案,因为它不会覆盖整个样式属性,并且是 W3C 的工作方式。
    • 它的缺点是我不能在 camelCase 中使用属性名称,例如 boxShadow
    • @Pavan 使用连字符形式很容易,或者如果您需要自动转换它,只需编写一个函数。
    【解决方案3】:

    我相信这样做的唯一方法是将样式添加为带有“!important”后缀的新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('td.EvenRow a {display:inline !important;}')
    

    使用上述方法添加的规则将(如果您使用 !important 后缀)覆盖其他先前设置的样式。如果您不使用后缀,请务必考虑“specificity”等概念。

    【讨论】:

    • 这可以用单行代替。见下文:stackoverflow.com/questions/462537/…
    • 如何找到真正触发样式的选择器?我认为这需要解析所有样式表,这是一项非常艰巨的工作。
    【解决方案4】:

    以@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 中的 camelCase。

    【讨论】:

    • 不妨使用更好的选择:element.style.setProperty
    【解决方案5】:

    如果你想在 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 is supported for all major browsers.

    用例示例:

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

    Here is link to demo

    【讨论】:

    • 这个答案提供了哪些额外的信息或改进?
    • 这个函数简短易懂。您可以添加重要选项。它不会删除所有元素样式。它在元素样式属性中覆盖或添加单个样式。你不需要任何 JS 框架。最重要的是,这个功能在每个浏览器中都可以使用。
    【解决方案6】:

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

    this page with information on how to create a user style

    【讨论】:

    • 修改 css 只是我的 gm 扩展的一部分
    【解决方案7】:

    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>
    

    【讨论】:

    • 初始不重置很重要。您不是在设置 p 的颜色,而是设置 em 的颜色。事实上,将 color:initial 更改为 color:green 也可以。
    【解决方案8】:

    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)
    

    【讨论】:

      【解决方案9】:

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

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

      【讨论】:

        【解决方案10】:

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

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

        我的很简单,不过我附上一个jsBin,例如:

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

        首先我在 CSS 中将主体背景设置为黄色 !important,然后由 JS 覆盖为 darkPink。

        【讨论】:

          【解决方案11】:

          下面是一段使用jquery为style属性设置重要参数的sn-p代码。

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

          【讨论】:

            猜你喜欢
            • 2017-05-06
            • 1970-01-01
            • 2018-06-16
            • 1970-01-01
            • 2012-08-11
            • 1970-01-01
            • 1970-01-01
            • 2018-12-27
            • 1970-01-01
            相关资源
            最近更新 更多