[英]Using CSS !important with JavaScript
<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>
From the code above, how can I override css property by !important in the above style property from my JS code defined in script tag ? 从上面的代码中,如何在脚本标记中定义的JS代码中覆盖上述样式属性中的!important的css属性?
Note: We have some internal applications that have their styles declared important 注意:我们有一些内部应用程序声明其样式很重要
Try this: 试试这个:
function myFunction() {
var x = document.querySelectorAll("#testDiv p.example");
x[0].style.setProperty("background-color", "red", "important");
}
Here is 2 different script, one target an element's CSS property and the other its style. 这是两个不同的脚本,一个目标是元素的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>
To override an important style in the style sheet you need to set the style attribute with js: 要覆盖样式表中的重要样式,需要使用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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.