我试图通过JS使用AddEventListener
和.style
属性获取来切换两个div的背景颜色。 但是,我可以在第一个分区中这样做,但是在第二个分区中不行。 为什么? 代码是一样的,元素是一样的,那为什么只发生在第一个分区???
null
document.querySelector('button').addEventListener("click", function(){
document.querySelector('div').style.background === "orange"
? document.querySelector('div').style.background = "pink"
: document.querySelector('div').style.background = "orange";
});
div {
width:200px;
height:200px;
margin:20px;
border:2px solid black;
display:inline-block;
background:orange;
}
<button>ok</button>
<div></div>
<div></div>
null
QuerySelector
返回第一个匹配元素。 使用QuerySelectorAll
,它将返回所有匹配元素的集合。
然后,您将需要迭代该集合,并在集合中的每个单独元素上设置样式
null
const divs = document.querySelectorAll('div');
const btn = document.querySelector('button');
let color;
btn.addEventListener("click", function(){
divs.forEach(d => {
if (!d.style.background || d.style.background === 'orange')
color = 'pink';
else
color = 'orange';
d.style.background = color;
})
});
div {
width: 200px;
height: 200px;
margin: 20px;
border: 2px solid black;
display: inline-block;
background: orange;
}
<button>ok</button>
<div></div>
<div></div>
您可以使用foreach()
循环并检查列表中的每个元素。 QuerySelector
获取它找到的第一个元素,而QuerySelectorAll
获取所有元素并将它们放入节点列表中,它看起来如下所示,然后[element1,element2,Element3...]
以便您可以循环遍历
null
document.querySelector('button').addEventListener("click", function(){
document.querySelectorAll('div').forEach(element => {
!element.style.background || element.style.background ==="orange"
? element.style.background = "pink"
: element.style.background = "orange";
})
});
div {
width:200px;
height:200px;
margin:20px;
border:2px solid black;
display:inline-block;
background:orange;
}
<button>ok</button>
<div></div>
<div></div>
您应该与QuerySelectorAll
和foreach
函数一起使用。 像这样:
null
document.querySelector('button').addEventListener("click", function() {
document.querySelectorAll('div').forEach(p => {
p.style.background == "orange" ?
p.style.background = "pink" :
p.style.background = "orange";
});
});
div {
width: 200px;
height: 200px;
margin: 20px;
border: 2px solid black;
display: inline-block;
background: orange;
}
<button>ok</button>
<div></div>
<div></div>