Javascript setTimeot不起作用
我试图将元素设置为显示:无;5秒后,但函数立即启动,所以我想知道setTimeout有什么问题 我已经在网络上搜索了很多来找到这个漏洞,但是我找到的每一个来源,他们都说我应该使用SetTimeout,因为我正在使用它。如果有任何答案,我将不胜感激Javascript setTimeot不起作用,javascript,settimeout,Javascript,Settimeout,我试图将元素设置为显示:无;5秒后,但函数立即启动,所以我想知道setTimeout有什么问题 我已经在网络上搜索了很多来找到这个漏洞,但是我找到的每一个来源,他们都说我应该使用SetTimeout,因为我正在使用它。如果有任何答案,我将不胜感激 var sideholder=document.getElementById(“简介持有者”); window.onload=函数ut(){ sideholder.style.display=“无”; } 设置超时(ut,5000)您正在将函数设置为
var sideholder=document.getElementById(“简介持有者”);
window.onload=函数ut(){
sideholder.style.display=“无”;
}
设置超时(ut,5000)代码>您正在将函数设置为window.onload
的值,它将在加载窗口后运行。但是,在此之前,JavaScript运行时将转到下一行,这是您尝试在5秒钟后运行名为ut
的函数,但是由于您最初使用它的方式,该名称在此时没有意义
将代码更改为以下内容,以便页面加载后,它将计数到5秒,然后运行函数,该函数将被声明为函数声明,而不是函数表达式
此外,在加载DOM之前,不应扫描DOM以查找“intro holder”(根据页面中的代码位置,可能不需要进行此更改)
您正确地使用了setTimeout,但window.onload被设置为与ut函数相等,使元素在pageload上消失(样式:none)。5秒后,ut运行并出错,因为元素已隐藏。window.onload应设置为等于setTimeout,以便浏览器知道在页面加载后立即运行它。之后可以定义ut函数。功能ut然后在5秒后运行
var sideholder=document.getElementById(“简介持有者”);
函数ut(){
sideholder.style.display=“无”;
}
window.onload=设置超时(ut,5000)代码>
#介绍支架{
高度:200px;
宽度:200px;
背景颜色:蓝色;
}
设置窗口。将加载到从setTimeout()
返回的整数没有多大意义。谢谢。是时候休息一下了。
// Get variables declared, but wait to initialize:
var sideholder = null;
var timer = null;
// When the window reports it is loaded, run a function that initiates the
// timer. Also, it's always a good idea to set a variable to the integer
// that represents the running timer in case you want to stop the timer
// later using clearTimeout(timer);
window.onload = function(){
// Now that the window is loaded, it's safe to go looking for DOM elements
sideholder = document.getElementById("intro-holder");
// Start the clock
timer = setTimeout(ut, 5000);
}
function ut() {
sideholder.style.display = "none";
}