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

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

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

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

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


当前回答

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

$("#elem").prop("style", "width: 100px !important"); // this is not supported in chrome
$("#elem").attr("style", "width: 100px !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等上运行。

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

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

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

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

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

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

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

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

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

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