Using CSS !important with JavaScript

前端 未结 3 704
不知归路
不知归路 2021-02-20 01:35



        
相关标签:
3条回答
  • 2021-02-20 01:53

    To override an important style in the style sheet you need to set the style attribute with js:

    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>

    0 讨论(0)
  • 2021-02-20 01:54

    Here is 2 different script, one target an element's CSS property and the other its style.

    <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>

    0 讨论(0)
  • 2021-02-20 02:04

    Try this:

    function myFunction() {
        var x = document.querySelectorAll("#testDiv p.example");
        x[0].style.setProperty("background-color", "red", "important");
    }
    
    0 讨论(0)
提交回复
热议问题