<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>
&#13;
从上面的代码中,如何在脚本标记中定义的JS代码中覆盖上述样式属性中的!important的css属性?
注意:我们有一些内部应用程序将其样式声明为重要
答案 0 :(得分:15)
试试这个:
function myFunction() {
var x = document.querySelectorAll("#testDiv p.example");
x[0].style.setProperty("background-color", "red", "important");
}
答案 1 :(得分:2)
这是两个不同的脚本,一个是元素的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>
&#13;
答案 2 :(得分:0)
要覆盖样式表中的重要样式,您需要使用js:
设置样式属性
function myFunction() {
var x = document.querySelectorAll("#testDiv p.example");
x[0].setAttribute('style', 'background-color: red !important');
}
&#13;
p.example {
background-color: blue !important;
}
&#13;
<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>
&#13;