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

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

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

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

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


当前回答

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

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

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

其他回答

无需考虑@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中创建一个新的类,例如:

.colorw{ color: white !important;}

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

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

问题已解决。

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

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

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

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

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

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

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