在继续其他代码之前,我正在使用await完成CSS转换。在[此小提琴] [1]中,fadeIn和fadeOut异步功能包括一个等待,用于解决转换结束的时间。
function transTo(el, className) {
return new Promise(resolve => {
el.ontransitionend = () => resolve();
el.classList.add(className);
});
}
function transFrom(el, className) {
return new Promise(resolve => {
el.ontransitionend = () => resolve();
el.classList.remove(className);
});
}
async function fadeIn(el) {
el.style.display = "block";
await transTo(el, "show");
}
async function fadeOut(el) {
await transFrom(el, "show");
el.style.display = "none";
}
const basic = document.querySelector(".blockA");
const btnFadeIn = document.querySelector(".btn.fade-in");
const btnFadeOut = document.querySelector(".btn.fade-out");
btnFadeIn.onclick = () => {
fadeIn(basic);
console.log("fade in");
}
btnFadeOut.onclick = () => {
fadeOut(basic);
console.log("fade out");
}
.basic {
position: absolute;
background: blue;
width: 100px;
height: 100px;
opacity: 0;
transition: opacity 5s ease-in-out;
}
.show {
opacity: 1;
}
.btn {
margin-left: 200px;
background: lightblue;
border-radius: 3px;
}
<div class="blockA"></div>
<button class="btn fade-in">Fade In</button>
<button class="btn fade-out">Fade Out</button>
fadeOut似乎可以正常工作,但是fadeIn不能正常工作。同样console.logs也可以立即执行,尽管我希望它们会延迟到过渡结束为止。显然,我缺少了一些东西。有人可以解释为什么它不能可靠地工作吗?
答案 0 :(得分:0)
您的onclick
处理程序还需要await
他们调用的函数。
赞:
btnFadeIn.onclick = async () => {
await fadeIn(basic);
console.log("fade in");
}
btnFadeOut.onclick = async () => {
await fadeOut(basic);
console.log("fade out");
}