我想我已经找到了解决办法。我已经把它变成了一个新功能:
jQuery.style(name, value, priority);
您可以使用它来获取.style('name')like 的值.css('name'),获取CSSStyleDeclarationwith .style(),还可以设置值,并能够将优先级指定为'important'。看到这个。
例子
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值的例子。我的问题是我已经!important在我的 CSS 中设置了宽度以避免与其他主题 CSS 发生冲突,但是我在 jQuery 中对宽度所做的任何更改都不会受到影响,因为它们会被添加到样式属性中。
兼容性
对于使用该setProperty功能的优先级设置,本文表示支持IE 9+等所有浏览器。我曾尝试使用 IE 8 但它失败了,这就是为什么我在我的函数中构建了对它的支持(见上文)。它可以在使用 的所有其他浏览器上运行setProperty,但它需要我的自定义代码才能在 < IE 9 中运行。