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

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

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

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

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


当前回答

问题是由jQuery不理解!重要属性,因此无法应用该规则。

您可能能够解决这个问题,并通过addClass()引用该规则来应用该规则:

.importantRule { width: 100px !important; }

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

或者使用attr():

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

然而,后一种方法将取消设置任何先前设置的内联样式规则。所以使用时要小心。

当然,有一个很好的论点是@Nick Craver的方法更容易/更明智。

上面的attr()方法稍作修改以保留原始样式字符串/财产,并按照falko在注释中的建议进行了修改:

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

其他回答

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

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

在CSS中:

#cheaterId { width: 100px;}

David Thomas的回答描述了一种使用$(“#elem”).attr(“style”,…)的方法,但警告称使用它将删除style属性中先前设置的样式。下面是一种使用attr()的方法,不会出现这种问题:

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

作为一项功能:

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

这是一个JS Bin演示。

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)

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

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

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

或者,如果需要,可以创建一个小型jQuery插件来实现这一点。该插件在其支持的参数中与jQuery自己的css()方法非常匹配:

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

这里是jsfiddle示例。

此解决方案将保留所有计算的javascript,并将重要标记添加到元素中:可以这样做(例如,如果需要设置重要标记的宽度)

$('exampleDiv').css('width', '');
//This will remove the width of the item
var styles = $('exampleDiv').attr('style');
//This will contain all styles in your item
//ex: height:auto; display:block;
styles += 'width: 200px !important;'
//This will add the width to the previous styles
//ex: height:auto; display:block; width: 200px !important;
$('exampleDiv').attr('style', styles);
//This will add all previous styles to your item