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

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

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

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

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


当前回答

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

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

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

更改行以使用.removeProperty函数,如elem[0].style.removeProperty('width');解决了这个问题。

其他回答

我们需要首先删除以前的样式。我使用正则表达式删除它。以下是更改颜色的示例:

var SetCssColorImportant = function (jDom, color) {
       var style = jDom.attr('style');
       style = style.replace(/color: .* !important;/g, '');
       jDom.css('cssText', 'color: ' + color + ' !important;' + style); }

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

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中工作。

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

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

三个工作示例

我也遇到过类似的情况,但在与.clost()进行了很长一段时间的斗争之后,我使用了.find()。

示例代码

// Allows contain functions to work, ignores case sensitivity

jQuery.expr[':'].contains = function(obj, index, meta, stack) {
    result = false;
    theList = meta[3].split("','");
    var contents = (obj.textContent || obj.innerText || jQuery(obj).text() || '')
    for (x=0; x<theList.length; x++) {
        if (contents.toLowerCase().indexOf(theList[x].toLowerCase()) >= 0) {
            return true;
        }
    }
    return false;
};

$(document).ready(function() {
    var refreshId = setInterval( function() {
        $("#out:contains('foo', 'test456')").find(".inner").css('width', '50px', 'important');
    }, 1000); // Rescans every 1000 ms
});

可供替代的

$('.inner').each(function () {
    this.style.setProperty('height', '50px', 'important');
});

$('#out').find('.inner').css({ 'height': '50px'});

工作:http://jsfiddle.net/fx4mbp6c/

如果它不那么相关,并且由于您正在处理一个元素#elem,那么您可以将其id更改为其他元素,并根据您的意愿对其进行样式设置。。。

$('#elem').attr('id', 'cheaterId');

在CSS中:

#cheaterId { width: 100px;}