使用 document.querySelector('.')。风格。更改不同 div 的 *两个* CSS 属性



作为前面问题的后续。我有以下脚本:

 document.querySelector('.clickme').addEventListener('click', function() {
     this.style.color = '#f00';
     this.style.backgroundColor = '#fff';
 });

。这意味着当单击/点击div .clickme时,脚本会更改.clickme自己的colorbackgroundColor属性。现在,相反,我需要脚本更改的不是.clickme's自己的属性,而是页面上另一个元素的colorbackgroundColor,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';
});

希望这有所帮助。

最新更新