仅当两个按钮都被单击时,我才想将 box1 的背景颜色更改为红色。
HTML:
<button id="button1">klick me</button>
<button id="button2">klick me</button>
<div class="box1"></div>
CSS:
.box1 {
width: 150px;
height: 150px;
background-color: blue;
}
.id2 {
background-color: red;
}
JavaScript:
function changeColor (){
let button1 = document.querySelector('#button1');
let button2 = document.querySelector('#button2');
let box1 = document.querySelector('.box1');
if(this.id === 'button1'){
box1.classList.toggle('id2');
}
}
button1.addEventListener('click', changeColor);
button2.addEventListener('click', changeColor);
前面的代码按预期工作。如果单击button1,box1 的颜色将变为红色。
所以我尝试了以下 if 语句来实现仅当单击两个按钮时颜色才会更改:
if(this.id === 'button1' && this.id === 'button2' ){
box1.classList.toggle('id2');
}
但不幸的是它不起作用。我缺少什么? 提前致谢!
最佳答案
你可以完成这个using promises :
function once (handler) {
return function one ({ type }) {
this.removeEventListener(type, one)
return handler.apply(this, arguments)
}
}
function when (type, selector) {
return new Promise(resolve => {
document.querySelector(selector).addEventListener(type, once(resolve))
})
}
Promise.all([
when('click', '#button1'),
when('click', '#button2')
]).then(function () {
document.querySelector('.box1').classList.toggle('id2')
})
.box1 {
width: 150px;
height: 150px;
background-color: blue;
}
.id2 {
background-color: red;
}
<button id="button1">click me</button>
<button id="button2">click me</button>
<div class="box1"></div>
如果将 Promise 链放入 async function 中,则可以扩展它以重复切换。并使用 while
循环:
function once (handler) {
return function one ({ type }) {
this.removeEventListener(type, one)
return handler.apply(this, arguments)
}
}
function when (type, selector) {
return new Promise(resolve => {
document.querySelector(selector).addEventListener(type, once(resolve))
})
}
async function toggler () {
const box = document.querySelector('.box1')
while (true) {
await Promise.all([
when('click', '#button1'),
when('click', '#button2')
])
box.classList.toggle('id2')
}
}
toggler()
.box1 {
width: 150px;
height: 150px;
background-color: blue;
}
.id2 {
background-color: red;
}
<button id="button1">click me</button>
<button id="button2">click me</button>
<div class="box1"></div>
关于javascript - 仅当单击两个按钮时如何操作元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54428895/