如何使用.css()应用!important?

JavaScript

卡卡西十三

2020-03-11

I am having trouble applying a style that is !important. I’ve tried:

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

This does nothing; no width style whatsoever is applied. Is there a jQuery-ish way of applying such a style without having to overwrite cssText (which would mean I’d need to parse it first, etc.)?

Edit: I should add that I have a stylesheet with an !important style that I am trying to override with an !important style inline, so using .width() and the like does not work since it gets overridden by my external !important style.

Also, the value that will override the previous value is computed, so I cannot simply create another external style.

第639篇《如何使用.css()应用!important?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

9个回答
凯LEY 2020.03.11

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

泡芙阿飞斯丁 2020.03.11

我还发现某些元素或附加组件(如Bootstrap)具有一些特殊的类情况,它们不能与!important或其他变通方法(如)配合使用.addClass/.removeClass,因此您必须将它们打开/关闭。

例如,如果您使用类似<table class="table-hover">的方法来成功修改诸如行颜色之table-hover类的元素的唯一方法是像这样切换类的开/关

$(your_element).closest("table").toggleClass("table-hover");

希望这种解决方法对某人有所帮助!:)

蓝染大人 2020.03.11

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

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

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

要么:

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

我会假设您尝试时未添加!important

内联CSS(这是JavaScript添加样式的方式)将覆盖样式表CSS。我很确定,即使样式表CSS规则具有,也是如此!important

另一个问题(也许是一个愚蠢的问题,但必须提出。):您正在尝试处理的元素display:block;还是display:inline-block;

不了解您在CSS方面的专业知识...内联元素并不总是表现出预期的效果。

null 2020.03.11

像这样做:

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

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

TomGil村村 2020.03.11

代替使用该css()函数,请尝试使用该addClass()函数:

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

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

您可以通过两种方式实现此目的:

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

你可以这样做:

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

使用“ cssText”作为属性名称,并使用任何要添加到CSS的值作为其名称。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android