简体   繁体   English

覆盖 !important 风格

[英]Overriding !important style

Title pretty much sums it up.标题几乎总结了它。

The external style sheet has the following code:外部样式表具有以下代码:

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

I have tried using:我试过使用:

element.style.display = "inline";

and

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

but neither works.但两者都不起作用。 Is it possible to override an !important style using javascript.是否可以使用 javascript 覆盖 !important 样式。

This is for a greasemonkey extension, if that makes a difference.这是一个greasemonkey 扩展,如果这有区别的话。

There are a couple of simple one-liners you can use to do this.您可以使用几个简单的单线来执行此操作。

  1. Set a "style" attribute on the element:在元素上设置“样式”属性

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

or...或者...

  1. Modify the cssText property of the style object:修改style对象的cssText属性:

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

Either will do the job.要么会做这项工作。

=== ===

I've written a jQuery plugin called "important" to manipulate !important rules in elements, : http://github.com/premasagar/important我编写了一个名为“important”的 jQuery 插件来操作元素中的!important规则,: http : //github.com/premasagar/important

=== ===

Edit: As shared in the comments, the standard CSSOM interface (the API for JavaScript to interact with CSS) provides the setProperty method:编辑:正如评论中所分享的,标准 CSSOM 接口(用于与 CSS 交互的 JavaScript 的 API)提供了setProperty方法:

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

Eg:例如:

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

element.style has a setProperty method that can take the priority as a third parameter: element.style有一个setProperty方法,可以将优先级作为第三个参数:

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

It didn't work in old IEs but it should be fine in current browsers.在旧 IE 中不起作用,但在当前浏览器中应该没问题

I believe the only way to do this it to add the style as a new CSS declaration with the '!important' suffix.我相信唯一的方法是将样式添加为带有 '!important' 后缀的新 CSS 声明。 The easiest way to do this is to append a new <style> element to the head of document:最简单的方法是在文档的头部附加一个新的 <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;}')

The rules added with the above method will (if you use the !important suffix) override other previously set styling.使用上述方法添加的规则(如果您使用 !important 后缀)将覆盖其他先前设置的样式。 If you're not using the suffix then make sure to take concepts like ' specificity ' into account.如果您不使用后缀,请确保将“特殊性”等概念考虑在内。

Building on @Premasagar's excellent answer;以@Premasagar 的出色回答为基础; if you don't want to remove all the other inline styles use this如果您不想删除所有其他内联样式,请使用此

//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' : '') + ';');
}

Can't use removeProperty() because it wont remove !important rules in Chrome.不能使用removeProperty()因为它不会删除 Chrome 中的!important规则。
Can't use element.style[property] = '' because it only accepts camelCase in FireFox.不能使用element.style[property] = ''因为它在 FireFox 中只接受驼峰式大小写。

Better method I just discovered: try to be more specific than the page CSS with your selectors. 我刚刚发现的更好的方法:尝试比使用选择器的页面CSS更具体。 I just had to do this today, and it works like a charm! 我今天只需要这样做,它就像一个魅力! More info on the W3C site: http://www.w3.org/TR/CSS2/cascade.html#specificity W3C网站上的更多信息: http : //www.w3.org/TR/CSS2/cascade.html#specificity

If you want to update / add single style in DOM Element style attribute you can use this function:如果要在 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 . style.cssText支持所有主流浏览器

Use case example:用例示例:

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

Here is link to demo这是演示的链接

If all you are doing is adding css to the page, then I would suggest you use the Stylish addon, and write a user style instead of a user script, because a user style is more efficient and appropriate.如果您所做的只是向页面添加 css,那么我建议您使用 Stylish 插件,并编写用户样式而不是用户脚本,因为用户样式更有效和更合适。

See this page with information on how to create a user style请参阅此页面,了解有关如何创建用户样式的信息

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

use initial property in css3在 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/ https://jsfiddle.net/xk6Ut/256/

One option to override CSS class in JavaScript is using an ID for the style element so that we can update the CSS class在 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)

Rather than injecting style, if you inject a class(for eg: 'show') through java script, it will work.如果你通过java脚本注入一个类(例如:'show'),而不是注入样式,它就会起作用。 But here you need css like below.但在这里你需要像下面这样的 css。 the added class css rule should be below your original rule.添加的 class css 规则应低于您的原始规则。

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

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

There we have another possibility to remove a property value from the CSS.我们还有另一种可能从 CSS 中删除属性值。

Like using the replace method in js.就像在js中使用replace方法一样。 But you have to know exactly the ID of the style, or you can write a for loop to detecting that by (count styles on the page, then check if any of those 'includes' or 'match' an !important value. & you can count also - how much contains them, or just simply write a global [regexp: /str/gi] replacing method)但是您必须确切地知道样式的 ID,或者您可以编写一个 for 循环来检测它(计算页面上的样式,然后检查这些“包含”或“匹配”中的任何一个是否为!important值。&您也可以计算 - 有多少包含它们,或者只是简单地编写一个全局 [regexp: /str/gi] 替换方法)

Mine is very simple, but I attach a jsBin, for example:我的很简单,但是我附上了一个jsBin,例如:

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

First I set the body background in CSS for yellow !important , then I overrided by JS for darkPink.首先,我在 CSS 中为 Yellow !important设置了正文背景,然后我用 JS 覆盖了 darkPink。

Below is a snippet of code to set the important parameter for the style attribute using jquery.下面是一段代码,用于使用 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,";"));
};

Usage is pretty simple.Just pass an object containing all the attributes you want to set as important.用法非常简单。只需传递一个包含您要设置为重要的所有属性的对象。

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

There are two additional options.还有两个附加选项。

1.To just add important parameter to already present style attribute pass empty string. 1. 将重要参数添加到已经存在的样式属性中,传递空字符串。

2.To add important param for all attributes present dont pass anything. 2.为所有存在的属性添加重要参数,不要传递任何东西。 It will set all attributes as important.它会将所有属性设置为重要。

Here is it live in action.这是它的现场直播。 http://codepen.io/agaase/pen/nkvjr http://codepen.io/agaase/pen/nkvjr

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

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