作为前面问题的后续。我有以下脚本:
document.querySelector('.clickme').addEventListener('click', function() {
this.style.color = '#f00';
this.style.backgroundColor = '#fff';
});
。这意味着当单击/点击div .clickme
时,脚本会更改.clickme
自己的color
和backgroundColor
属性。现在,相反,我需要脚本更改的不是.clickme's
自己的属性,而是页面上另一个元素的color
和backgroundColor
,div类(我们称之为(.zebra
。应该如何修改脚本来实现这一点?(单击/点击的目标仍将是.clickme
。
您可以在单击事件处理程序中使用document.querySelector('.zebra')
document.querySelector('.clickme').addEventListener('click', function() {
this.style.color = '#f00';
this.style.backgroundColor = '#fff';
document.querySelector('.zebra').style.color = 'blue';
document.querySelector('.zebra').style.backgroundColor = 'grey';
});
document.querySelector('.clickme').addEventListener('click', function() {
this.style.color = '#f00';
this.style.backgroundColor = '#fff';
document.querySelector('.zebra').style.color = 'blue';
document.querySelector('.zebra').style.backgroundColor = 'grey';
});
<div class='clickme'>Click me</div>
<div class='zebra'>Zebra</div>
找到另一个带有document.querySelector(".zebra")
的元素并更改其颜色和背景颜色:
document.querySelector('.clickme').addEventListener('click', function() {
let zebra = document.querySelector('.zebra')
zebra.style.color = '#f00';
zebra.style.backgroundColor = '#fff';
});
希望这有所帮助。