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

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

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

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

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


当前回答

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

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

在CSS中:

#cheaterId { width: 100px;}

其他回答

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

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)

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

示例1:

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

示例2:

elem.style.cssText='color: red !important;'

无需考虑@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等上运行。

它可能适合也可能不适合您的情况,但您可以在许多此类情况下使用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;}