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

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

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

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

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


可以直接使用.width()设置宽度,如下所示:

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

更新征求意见:您也有这个选项,但它将替换元素上的所有css,因此不确定它是否更可行:

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

问题是由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;' });

我想你没有添加就尝试了!重要的

内联CSS(这是JavaScript添加样式的方式)覆盖样式表CSS。我很确定,即使样式表CSS规则有这种情况!重要的

另一个问题(可能是一个愚蠢的问题,但必须要问。):您正在尝试的元素是否显示:block;或显示:内联块;?

不知道你在CSS方面的专业知识。。。内联元素的行为并不总是如您所期望的那样。


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

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

在CSS中:

#cheaterId { width: 100px;}

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

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


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演示。


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

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

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

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

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

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

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

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

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


它可能适合也可能不适合您的情况,但您可以在许多此类情况下使用CSS选择器。

例如,如果您希望.cssText的第3个和第6个实例具有不同的宽度,可以编写:

.cssText:nth-of-type(3), .cssText:nth-of-type(6) {width:100px !important;}

Or:

.container:nth-of-type(3).cssText, .container:nth-of-type(6).cssText {width:100px !important;}

这样做:

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

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');解决了这个问题。


无需考虑@AramKocharyan的答案的复杂性,也无需动态插入任何样式标签。

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

// 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' : '') + ';');
}

无法使用removeProperty(),因为它不会删除!Chrome中的重要规则。无法使用element.style[property]='',因为它只接受Firefox中的camelCase。

您可能会用jQuery缩短这个过程,但这个普通函数将在现代浏览器、InternetExplorer8等上运行。


另一种解决此问题的简单方法是添加样式属性:

$('.selector').attr('style', 'width:500px !important');

我还发现某些元素或插件(如Bootstrap)有一些特殊的类情况,它们不能很好地使用!重要的或其他解决方法,如.addClass/.removeClass,因此您必须打开/关闭它们。

例如,如果您使用类似<table class=“table hover”>的方法,成功修改行颜色等元素的唯一方法是打开/关闭table hover类,如下所示

$(your_element)最近(“table”).tggleClass(“table hover”);

希望这项工作对某人有帮助!:)


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

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

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


您可以这样做:

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

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


不要使用css()函数,请尝试addClass()函数:

  <script>
  $(document).ready(function() {
    $("#example").addClass("exampleClass");
  });
  </script>

  <style>
  .exampleClass{
    width:100% !important;
    height:100% !important;
  }
  </style>

可能是这样的:

隐藏物

var node = $('.selector')[0];
OR
var node = document.querySelector('.selector');

设置CSS

node.style.setProperty('width', '100px', 'important');

删除CSS

node.style.removeProperty('width');
OR
node.style.width = '';

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

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

对于这个问题,我认为最简单、最好的解决方案是使用addClass()而不是.css()或.attr()。

例如:

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

在CSS文件中:

.importantClass {
    width: 100px !important;
}

仅供参考,它不起作用,因为jQuery不支持它。2012年提交了一张罚单(#11173$(elem).css(“property”,“value!important”)失败),最终被关闭为WONTFIX。


我们可以使用setProperty或cssText来添加!对于使用JavaScript的DOM元素来说很重要。

示例1:

elem.style.setProperty ("color", "green", "important");

示例2:

elem.style.cssText='color: red !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)

当“事件”时,我尝试更改菜单项的文本颜色时遇到了同样的问题。当我遇到同样的问题时,我发现的最佳方法是:

第一步:在CSS中创建一个新的类,例如:

.colorw{ color: white !important;}

最后一步:使用addClass方法应用该类,如下所示:

$('.menu-item>a').addClass('colorw');

问题已解决。


三个工作示例

我也遇到过类似的情况,但在与.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/


我认为它工作正常,可以覆盖之前的任何其他CSS(this:DOM元素):

this.setAttribute('style', 'padding:2px !important');

最安全的解决方法是添加一个类,然后在CSS中执行魔术:-),addClass()和removeClass()应该完成这项工作。


此解决方案将保留所有计算的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

大多数这些答案现在都过时了,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示例。