后续an earlier question。我有以下脚本:
document.querySelector('.clickme').addEventListener('click', function() {
this.style.color = '#f00';
this.style.backgroundColor = '#fff';
});
......,这意味着当单击/轻按div .clickme
时,脚本将更改.clickme
自己的color
和backgroundColor
属性。现在,我需要的脚本不是更改.clickme's
自己的属性,而是更改页面上另一个元素的div类的color
和backgroundColor
(让我们称呼它){{1 }}。应该如何修改脚本以实现该目标? (点击/点击的目标仍然是.zebra
。)
答案 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';
});
希望这会有所帮助。