我试图在单击元素时发生一系列样式更改时创建一个简单的函数。
我想在我所做的两次样式更改之间添加 4 秒的延迟。我发现了一些在函数之前和之后添加延迟的方法,但不在函数内部添加延迟,如何实现此目的?
我的代码:
const btnEl = document.getElementById("btnel")
const subtl = document.getElementById("chp1sub")
document.getElementById("chp1sub").style.backgroundColor = "red";
btnEl.addEventListener("click", function(){
subtl.style.backgroundColor = "blue"
// 4 second delay here before running next line
subtl.style.transform = "translateY(-90px)"
})
非常感谢对此的任何建议
最佳答案
您可以简单地使用setTimeout
方法,它会在您设置的时间(以毫秒为单位)后运行函数。为了实现你所需要的,你必须为其设置一个匿名函数。
示例
setTimeout(() => {
/* Code to run after 4 seconds */
}, 4000)
使用您的代码
const btnEl = document.getElementById("btnel")
const subtl = document.getElementById("chp1sub")
document.getElementById("chp1sub").style.backgroundColor = "red";
btnEl.addEventListener("click", function(){
subtl.style.backgroundColor = "blue"
setTimeout(() => {
// 4 second delay here before running next line
subtl.style.transform = "translateY(-90px)"
}, 4000)
})
关于javascript - 如何在 Javascript 函数中添加延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72140480/