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

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

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

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

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


当前回答

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

其他回答

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

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

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

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

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

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

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

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

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

$("#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等上运行。