Javascript 如何使用 .css() 应用 !important?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2655925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:20:26  来源:igfitidea点击:

How to apply !important using .css()?

javascriptjqueryhtmlcss

提问by mkoryak

I am having trouble applying a style that is !important. I've tried:

我在应用!important. 我试过了:

$("#elem").css("width", "100px !important");

This does nothing; no width style whatsoever is applied. Is there a jQuery-ish way of applying such a style without having to overwrite cssText(which would mean I'd need to parse it first, etc.)?

什么都不做;没有应用任何宽度样式。是否有一种 jQuery 风格的方式来应用这种样式而不必覆盖cssText(这意味着我需要先解析它等)?

Edit: I should add that I have a stylesheet with an !importantstyle that I am trying to override with an !importantstyle inline, so using .width()and the like does not work since it gets overridden by my external !importantstyle.

编辑:我应该补充一点,我有一个样式表!important,我试图用!important内联样式覆盖该样式,因此使用.width()等不起作用,因为它被我的外部!important样式覆盖。

Also, the value that will override the previous value is computed, so I cannot simply create another external style.

此外,将覆盖先前值的值是计算的,所以我不能简单地创建另一个外部样式。

采纳答案by mkoryak

Most of these answers are now outdated, IE7 support is not an issue.

大多数这些答案现在已经过时,IE7 支持不是问题。

The best way to do this that supports IE11+ and all modern browsersis:

支持 IE11+ 和所有现代浏览器的最佳方法是:

const $elem = $("#elem");
$elem[0].style.setProperty('width', '100px', 'important');


Or if you want, you can create a small jQuery plugin that does this. This plugin closely matches jQuery's own css()method in the parameters it supports:

或者,如果您愿意,您可以创建一个小型 jQuery 插件来执行此操作。这个插件css()在它支持的参数上与 jQuery 自己的方法非常匹配:

/**
 * Sets a CSS style on the selected element(s) with !important priority.
 * This supports camelCased CSS style property names and calling with an object 
 * like the jQuery `css()` method. 
 * Unlike jQuery's css() this does NOT work as a getter.
 * 
 * @param {string|Object<string, string>} name
 * @param {string|undefined} value
 */   
jQuery.fn.cssImportant = function(name, value) {
  const $this = this;
  const applyStyles = (n, v) => {
    // Convert style name from camelCase to dashed-case.
    const dashedName = n.replace(/(.)([A-Z])(.)/g, (str, m1, upper, m2) => {
      return m1 + "-" + upper.toLowerCase() + m2;
    }); 
    // Loop over each element in the selector and set the styles.
    $this.each(function(){
      this.style.setProperty(dashedName, v, 'important');
    });
  };
  // If called with the first parameter that is an object,
  // Loop over the entries in the object and apply those styles. 
  if(jQuery.isPlainObject(name)){
    for(const [n, v] of Object.entries(name)){
       applyStyles(n, v);
    }
  } else {
    // Otherwise called with style name and value.
    applyStyles(name, value);
  }
  // This is required for making jQuery plugin calls chainable.
  return $this;
};
// Call the new plugin:
$('#elem').cssImportant('height', '100px');

// Call with an object and camelCased style names:
$('#another').cssImportant({backgroundColor: 'salmon', display: 'block'});

// Call on multiple items:
$('.item, #foo, #bar').cssImportant('color', 'red');

Example jsfiddle here.

示例 jsfiddle 在这里

回答by David says reinstate Monica

The problem is caused by jQuery not understanding the !importantattribute, and as such fails to apply the rule.

问题是由 jQuery 不理解!important属性引起的,因此无法应用规则。

You might be able to work around that problem, and apply the rule by referring to it, via addClass():

您也许可以解决该问题,并通过引用它来应用规则addClass()

.importantRule { width: 100px !important; }

$('#elem').addClass('importantRule');

Or by using attr():

或者通过使用attr()

$('#elem').attr('style', 'width: 100px !important');

The latter approach would unset any previously set in-line style rules, though. So use with care.

不过,后一种方法会取消任何先前设置的内嵌样式规则。所以请谨慎使用。

Of course, there's a good argument that @Nick Craver's method is easier/wiser.

当然,有一个很好的论据认为@Nick Craver 的方法更简单/更明智。

The above, attr()approach modified slightly to preserve the original stylestring/properties, and modified as suggested by falkoin a comment:

上面的attr()方法稍微修改以保留原始style字符串/属性,并按照falko在评论中的建议进行修改:

$('#elem').attr('style', function(i,s) { return (s || '') + 'width: 100px !important;' });

回答by Aram Kocharyan

I think I've found a real solution. I've made it into a new function:

我想我找到了一个真正的解决方案。我已经把它变成了一个新功能:

jQuery.style(name, value, priority);

jQuery.style(name, value, priority);

You can use it to get values with .style('name')just like .css('name'), get the CSSStyleDeclaration with .style(), and also set values - with the ability to specify the priority as 'important'. See this.

您可以使用它来获取.style('name')类似的值.css('name'),获取 CSSStyleDeclaration.style()以及设置值 - 能够将优先级指定为“重要”。看到这个

Demo

演示

var div = $('someDiv');
console.log(div.style('color'));
div.style('color', 'red');
console.log(div.style('color'));
div.style('color', 'blue', 'important');
console.log(div.style('color'));
console.log(div.style().getPropertyPriority('color'));

Here's the output:

这是输出:

null
red
blue
important

The Function

功能

(function($) {    
  if ($.fn.style) {
    return;
  }

  // Escape regex chars with \
  var escape = function(text) {
    return text.replace(/[-[\]{}()*+?.,\^$|#\s]/g, "\$&");
  };

  // For those who need them (< IE 9), add support for CSS functions
  var isStyleFuncSupported = !!CSSStyleDeclaration.prototype.getPropertyValue;
  if (!isStyleFuncSupported) {
    CSSStyleDeclaration.prototype.getPropertyValue = function(a) {
      return this.getAttribute(a);
    };
    CSSStyleDeclaration.prototype.setProperty = function(styleName, value, priority) {
      this.setAttribute(styleName, value);
      var priority = typeof priority != 'undefined' ? priority : '';
      if (priority != '') {
        // Add priority manually
        var rule = new RegExp(escape(styleName) + '\s*:\s*' + escape(value) +
            '(\s*;)?', 'gmi');
        this.cssText =
            this.cssText.replace(rule, styleName + ': ' + value + ' !' + priority + ';');
      }
    };
    CSSStyleDeclaration.prototype.removeProperty = function(a) {
      return this.removeAttribute(a);
    };
    CSSStyleDeclaration.prototype.getPropertyPriority = function(styleName) {
      var rule = new RegExp(escape(styleName) + '\s*:\s*[^\s]*\s*!important(\s*;)?',
          'gmi');
      return rule.test(this.cssText) ? 'important' : '';
    }
  }

  // The style function
  $.fn.style = function(styleName, value, priority) {
    // DOM node
    var node = this.get(0);
    // Ensure we have a DOM node
    if (typeof node == 'undefined') {
      return this;
    }
    // CSSStyleDeclaration
    var style = this.get(0).style;
    // Getter/Setter
    if (typeof styleName != 'undefined') {
      if (typeof value != 'undefined') {
        // Set style property
        priority = typeof priority != 'undefined' ? priority : '';
        style.setProperty(styleName, value, priority);
        return this;
      } else {
        // Get style property
        return style.getPropertyValue(styleName);
      }
    } else {
      // Get CSSStyleDeclaration
      return style;
    }
  };
})(jQuery);

See thisfor examples of how to read and set the CSS values. My issue was that I had already set !importantfor the width in my CSS to avoid conflicts with other theme CSS, but any changes I made to the width in jQuery would be unaffected since they would be added to the style attribute.

请参见有关如何读取和设置CSS值的例子。我的问题是我已经!important在我的 CSS 中设置了宽度以避免与其他主题 CSS 发生冲突,但是我在 jQuery 中对宽度所做的任何更改都不会受到影响,因为它们会被添加到样式属性中。

Compatibility

兼容性

For setting with the priority using the setPropertyfunction, This Articlesays there is support for IE 9+ and all other browsers. I have tried with IE 8 and it has failed, which is why I built support for it in my functions (see above). It will work on all other browsers using setProperty, but it will need my custom code to work in < IE 9.

对于使用该setProperty功能的优先级设置,本文说支持IE 9+和所有其他浏览器。我曾尝试使用 IE 8 但它失败了,这就是为什么我在我的函数中构建了对它的支持(见上文)。它可以在使用 setProperty 的所有其他浏览器上运行,但它需要我的自定义代码才能在 < IE 9 中运行。

回答by Nick Craver

You can set the width directly using .width()like this:

您可以.width()像这样直接设置宽度:

$("#elem").width(100);

Updated for comments:You have this option as well, but it'll replace all css on the element, so not sure it's any more viable:

更新评论:你也有这个选项,但它会替换元素上的所有 css,所以不确定它是否更可行:

$('#elem').css('cssText', 'width: 100px !important');

回答by BettaSplendens

const elem = $("#elem");
elem[0].style.removeAttribute('width');
elem[0].style.setProperty('width', '100px', 'important');

Note: Using Chrome may return an error such as:

注意:使用 Chrome 可能会返回一个错误,例如:

elem[0].style.removeAttribute is not a function

elem[0].style.removeAttribute 不是函数

Changing the line to use the .removePropertyfunction such as to elem[0].style.removeProperty('width');fixed the issue.

更改线路以使用.removeProperty诸如elem[0].style.removeProperty('width');修复问题的功能。

回答by Rory O'Kane

David Thomas's answerdescribes a way to use $('#elem').attr('style', …), but warns that using it will delete previously-set styles in the styleattribute. Here is a way of using attr()without that problem:

David Thomas 的回答描述了一种使用 的方法$('#elem').attr('style', …),但警告使用它会删除style属性中先前设置的样式。这是一种attr()没有这个问题的使用方法:

var $elem = $('#elem');
$elem.attr('style', $elem.attr('style') + '; ' + 'width: 100px !important');

As a function:

作为一个函数:

function addStyleAttribute($element, styleAttribute) {
    $element.attr('style', $element.attr('style') + '; ' + styleAttribute);
}
addStyleAttribute($('#elem'), 'width: 100px !important');

Here is a JS Bin demo.

这是一个JS Bin 演示

回答by Nate

After reading other answers and experimenting, this is what works for me:

阅读其他答案并进行实验后,这对我有用:

$(".selector")[0].style.setProperty( 'style', 'value', 'important' );

This doesn't work in IE 8 and under, though.

但是,这在 IE 8 及以下版本中不起作用。

回答by hawkeye126

You can do this:

你可以这样做:

$("#elem").css("cssText", "width: 100px !important;");

Using "cssText" as the property name and whatever you want added to the CSS as its value.

使用“cssText”作为属性名称,并使用您想要添加到 CSS 中的任何内容作为其值。

回答by kva

You can achieve this in two ways:

您可以通过两种方式实现这一点:

$("#elem").prop("style", "width: 100px !important"); // this is not supported in chrome
$("#elem").attr("style", "width: 100px !important");

回答by Hashbrown

There's no need to go to the complexity of @AramKocharyan's answer, nor the need to insert any style tags dynamically.

不需要去复杂的@AramKocharyan 的答案,也不需要动态插入任何样式标签。

Just overwrite style, butyou don't have to parse anything, why would you?

只需覆盖样式,您不必解析任何内容,为什么要?

// Accepts the hyphenated versions (i.e. not 'cssFloat')
function 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 won't remove !importantrules in Chrome.
Can't use element.style[property] = '', because it only accepts camelCase in Firefox.

不能使用removeProperty(),因为它不会删除!importantChrome中的规则。
不能使用element.style[property] = '',因为它只接受 Firefox 中的驼峰命名。

You could probably make this shorter with jQuery, but this vanilla function will run on modern browsers, Internet Explorer 8, etc.

你可以用 jQuery 缩短这个时间,但这个普通的函数将在现代浏览器、Internet Explorer 8 等上运行。

回答by kebyang

Here is what I did after encountering this problem...

这是我遇到这个问题后所做的......

var origStyleContent = jQuery('#logo-example').attr('style');
jQuery('#logo-example').attr('style', origStyleContent + ';width:150px !important');