Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

javascript - Using document.querySelector('.').style. to change *two* CSS properties of a different div

In follow-up to an earlier question. I have the following script:

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

...which means when the div .clickme is clicked/tapped, the script changes .clickme's own color and backgroundColor properties. Now, instead, I need the script to change not .clickme's own properties, but the color and backgroundColor of another element on the page, a div class (let's call it) .zebra. How should the script be modified to achieve that? (The target of the click/tap would still be .clickme.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use document.querySelector('.zebra') inside click event handler

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...