使用document.querySelector('。')。style。更改另一个div的*两个* CSS属性

时间:2019-06-20 16:02:41

标签: javascript html css

后续an earlier question。我有以下脚本:

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

......,这意味着当单击/轻按div .clickme时,脚本将更改.clickme自己的colorbackgroundColor属性。现在,我需要的脚本不是更改.clickme's自己的属性,而是更改页面上另一个元素的div类的colorbackgroundColor(让我们称呼它){{1 }}。应该如何修改脚本以实现该目标? (点击/点击的目标仍然是.zebra。)

2 个答案:

答案 0 :(得分:2)

您可以在点击事件处理程序中使用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>

答案 1 :(得分:1)

使用document.querySelector(".zebra")找到另一个元素,并更改其颜色和背景颜色:

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

希望这会有所帮助。