使用JavaScript与CSS !important

38

<div id="testDiv">
  <h2 class="example">A heading with class="example"</h2>
  <p class="example">A paragraph with class="example".</p>
</div>

<button onclick="myFunction()">Try it</button>

<style>
  .example {
    background-color: green !important;
  }
</style>

<script>
  function myFunction() {
    var x = document.querySelectorAll("#testDiv p.example");
    x[0].style.backgroundColor = "red";
  }
</script>

从上面的代码中,我应该如何在script标签中定义的JS代码中使用!important覆盖上面的style属性中的css属性?

注意:我们有一些内部应用程序声明了important样式。


style.backgroundColor = "red !important" 不起作用吗? - evolutionxbox
不是这样的,当我使用 !important 时,CSS 没有生效,因为那不是正确的格式。 - Nagaraju Y
1
在我的应用程序中,我无法使用 .css 文件来使用样式,因此我必须使用 JavaScript 代码来覆盖现有的代码。上面给出的代码仅供参考。 - Nagaraju Y
3个回答

93

使用CSSStyleDeclaration.setProperty()尝试此代码:

function myFunction() {
    var x = document.querySelectorAll("#testDiv p.example");
    x[0].style.setProperty("background-color", "red", "important");
}

2
@Nagaraju_007 这个解决方案只会覆盖指定的属性,而我的和Pete的解决方案可能会覆盖整个样式,所以我给它点赞...并且要彻底测试它。 - Asons
我明白了,如果我们只想设置单个属性,那么@LGSon的代码很好;如果我们想要设置一组属性,那么你的代码就很好。 - Nagaraju Y
浏览器对此的支持似乎也不成问题:https://caniuse.com/mdn-api_cssstyledeclaration_setproperty - Gellweiler

3

这里有两个不同的脚本,一个针对元素的CSS属性,另一个针对其样式。

<div id="testDiv">
  <h2 class="example">A heading with class="example"</h2>
  <p class="example">A paragraph with class="example".</p>
</div>

<p>Click the button to add a background color to the first element in the document with class="example" (index 0).</p>

<button onclick="myFunction()">Try it</button>
<button onclick="myFunction2()">Try it 2</button>

<p><strong>Note:</strong> The querySelectorAll() method is not supported in Internet Explorer 8 and earlier versions.</p>

<script>
  function myFunction() {
    var x = document.querySelectorAll("#testDiv p.example");
    x[0].style.backgroundColor = "red";
  }
  function myFunction2() {
    var x = document.querySelectorAll("#testDiv p.example");
    x[0].style = "background-color: red !important";
  }
</script>


2

要覆盖样式表中的重要样式,您需要使用js设置style属性:

function myFunction() {
  var x = document.querySelectorAll("#testDiv p.example");
  x[0].setAttribute('style', 'background-color: red !important');
}
p.example {
  background-color: blue !important;
}
<div id="testDiv">
  <h2 class="example">A heading with class="example"</h2>
  <p class="example">A paragraph with class="example".</p>
</div>
<button onclick="myFunction()">Try it</button>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接