我有很多元素我用它們著色querySelectorAll然后我想用其中一個元素著色getElementById然后我再次使用querySelectorAll它再次為所有元素著色,問題是第二次它不起作用(顏色沒有改變querySelectorAll) .
還有其他方法可以做這樣的事情getElementsByClassName但我想使用上述方法的想法代碼更多地解釋了這個問題:
<!DOCTYPE html>
<html>
<body>
<div class="main">
<h2 class="ex" id="myH1">This is an example h2</h2>
<h2 class="ex" id="myH2">This is an example h2</h2>
<h2 class="ex" id="myH3">This is an example h2</h2>
</div>
<button type="button" onclick="myFunction()">Set text color all</button>
<button type="button" onclick="myFunction2()">Set text color one</button>
<script>
function myFunction2() {
var x = document.querySelectorAll(".main");
var i;
for(i=0;i<x.length;i )
{
x[i].style.color = "#00ff88";
}
}
function myFunction() {
document.getElementById("myH2").style.color = "#ff0000";
}
</script>
</body>
</html>
請先單擊全部設定文本顏色,然后單擊設定文本顏色,然后再次單擊全部設定文本顏色。
uj5u.com熱心網友回復:
只需h2在選擇器中添加也像:
var x = document.querySelectorAll(".main h2"); // add h2 here in the
然后顏色將始終設定在“相同”元素上,您的 CSS 將起作用。您面臨的問題是(正如塞巴斯蒂安在評論中提到的那樣)您一次設定顏色<div ...,另一次設定<h2 id="myH2"...
<!DOCTYPE html>
<html>
<body>
<div class="main">
<h2 class="ex" id="myH1">This is an example h2</h2>
<h2 class="ex" id="myH2">This is an example h2</h2>
<h2 class="ex" id="myH3">This is an example h2</h2>
</div>
<button type="button" onclick="myFunction2()">Set text color all</button>
<button type="button" onclick="myFunction()">Set text color one</button>
<script>
function myFunction2() {
var x = document.querySelectorAll(".main h2"); // add h2 here in the selector
var i;
for(i=0;i<x.length;i )
{
x[i].style.color = "#00ff88";
}
}
function myFunction() {
document.getElementById("myH2").style.color = "#ff0000";
}
</script>
</body>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/450670.html
下一篇:CSS樣式-無法在表格中居中文本
