我很难应用这样的风格!重要的我尝试过:

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

这没有任何作用;不应用任何宽度样式。有没有类似jQuery的方法来应用这样的样式而不必覆盖cssText(这意味着我需要先解析它,等等)?

编辑:我应该补充一下,我有一个带有!我试图用!重要的样式内联,因此使用.width()等不会起作用,因为它会被我的外部重写!重要的风格。

此外,将覆盖上一个值的值是计算出来的,因此我不能简单地创建另一个外部样式。


当前回答

此解决方案不覆盖以前的任何样式,它只应用您需要的样式:

var heightStyle = "height: 500px !important";
if ($("foo").attr('style')) {
  $("foo").attr('style', heightStyle + $("foo").attr('style').replace(/^height: [-,!,0-9,a-z, A-Z, ]*;/,''));
else {
  $("foo").attr('style', heightStyle);
}

其他回答

在头部附加样式的另一种方法:

$('head').append('<style> #elm{width:150px !important} </style>');

这将在所有CSS文件之后附加样式,因此它将比其他CSS文件具有更高的优先级,并将被应用。

在阅读了其他答案并进行了实验之后,这对我来说很有用:

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

不过,这在IE8及以下版本中不起作用。

这样做:

$("#elem").get(0).style.width= "100px!important";

https://jsfiddle.net/xk6Ut/256/

另一种方法是在JavaScript中动态创建和更新CSS类。要做到这一点,我们可以使用style元素,并且需要为style元素使用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)

我想我找到了解决办法。我把它变成了一个新功能:

jQuery.style(名称、值、优先级);

您可以使用它像.css('name')一样使用.style('name`)获取值,使用.style()获取CSSStyleDeclaration,还可以设置值,并可以将优先级指定为“重要”。看看这个。

实例

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'));

示例输出:

null
red
blue
important

功能

(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);

有关如何读取和设置CSS值的示例,请参阅本文。我的问题是我已经设定好了!我的CSS中的宽度对于避免与其他主题CSS冲突很重要,但我在jQuery中对宽度所做的任何更改都不会受到影响,因为它们将被添加到style属性中。

兼容性

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