我试图在页面加载后几秒钟向 HTML 元素(ID bland-html-element)添加和删除 HTML 类(.flashy-design)。
我的以下尝试没有注入(inject)该类。
setTimeout(function() {
function addFlashyDesign() {
var element = document.getElementById("bland-html-element");
element.classList.add("flashy-design");
}
}, 3000);
或
function startDelay(){
setTimeout(function() {
function addFlashyDesign() {
var element = document.getElementById("bland-html-element");
element.classList.add("flashy-design");
}
}, 3000);
};
window.onload = "startDelay();";
想法?
最佳答案
解释在代码中。您犯的主要错误是没有像您应该的那样使用回调函数。
let element = document.getElementById("bland-html-element");
// show after 2 seconds
// RECOMMENDATION: use window.setTimeout instead of setTimeout
// NOTE: use a callback function, not an embedded named function
window.setTimeout(function() {
element.classList.add("flashy-design");
}, 2000);
// hide after 3 seconds
window.setTimeout(function() {
element.classList.remove("flashy-design");
}, 3000);
#bland-html-element{
height: 200px;
width: 200px;
background-color: green;
display: none;
}
#bland-html-element.flashy-design{
display: block;
}
<div id="bland-html-element"></div>
PS:不要使用window.onload
。请改用 window.addEventListener('load', function(){})
。我没有在示例中的加载事件之后嵌入它,但您应该在 DOM 中存在 bland-html-element
之前运行代码,否则您将面临运行代码的风险。
关于javascript - 如何在页面加载后的特定时间添加和删除 HTML 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54380677/