问题描述
我有这个脚本,在其中突出显示单击的div及其父级,然后分别将它们再次设为白色。但是,我想停止连续单击,只允许单击一次直到setTimeout完成。基本上,用户应等待整个动画结束后再单击。
const alldivelements = document.querySelectorAll("div");
let timeout = 300;
alldivelements.forEach((div) => {
div.addEventListener("click",function (e) {
setTimeout(() => {
changeBg(this,true);
setTimeout(() => {
changeBg(this,false);
timeout = 300;
},timeout);
},timeout);
timeout += 300;
});
});
function changeBg(div,phase) {
if (phase) div.style.backgroundColor = "lightblue";
else div.style.backgroundColor = "#fff";
}
就我仔细研究了可能的解决方案之前,直到setTimeout方法才找到阻止点击事件的解决方案。任何详细的帮助将不胜感激。
编辑:对不起,如果引起混乱。如果您想对其进行测试,这是整个应用程序的链接:https://codesandbox.io/s/busy-goldstine-ope9w?file=/src/index.js
谢谢!
解决方法
您似乎正在尝试使其变得过于复杂。只需对每个元素使用布尔值即可跟踪点击是否有效:
const timeout = 300;
allDivElements.forEach((div) => {
let clickAllowed = true;
div.addEventListener("click",function (e) {
if (clickAllowed) {
clickAllowed = false;
changeBg(this,true);
setTimeout(() => {
changeBg(this,false);
clickAllowed = true;
},timeout);
}
});
});
,
- 使用
addEventListener
和removeEventListener
处理听众 - 处理完所有元素后,请使用
addEventListener
重新添加事件
- 递归也可以方便地遍历父元素:
const divs = document.querySelectorAll("div");
const EVT = (el,t,n,f,o = {}) => el.forEach(e => e[`${{on:"add",off:"remove"}[t]}EventListener`](n,o));
const changeBg = (div) => {
if ([...divs].indexOf(div) < 0) return EVT(divs,"on","click",clickHandler); // Add
div.style.backgroundColor = "lightblue";
setTimeout(() => {
div.style.backgroundColor = "white";
changeBg(div.parentElement); // Recursive call,this time pass the parent
},300);
};
const clickHandler = async(ev) => {
EVT(divs,"off",clickHandler); // Remove listeners
changeBg(ev.currentTarget); // Start
};
EVT(divs,clickHandler); // Add listeners
body {
font-family: sans-serif;
}
div {
border: 1px solid black;
padding: 5px;
background: #fff;
}
<div id="1">1
<div id="2">2
<div id="3">3
<div id="4">4
<div id="5">5
</div>
</div>
</div>
</div>
</div>