我的页面加载后如何运行settimeout?
我想在加载页面后运行一个超时功能以显示图像,但我不知道为什么它不运行。这是语法问题吗? 这是我的代码:
const screenshot = document.querySelector('#device-screenshot');
function loaded() {
console.log('loaded')
setTimeout(() => {screenshot.src = "dist/images/new-screenshot-2.jpeg"
}, 4000);
}
if (screenshot.complete) {
loaded()
} else {
screenshot.addEventListener('load', loaded)
screenshot.addEventListener('error', function() {
console.log('error')
})
}
I want to run a time out function to show an image once the page is loaded but I don't know why it's not running. Is this a matter of syntax?
Here's my code:
const screenshot = document.querySelector('#device-screenshot');
function loaded() {
console.log('loaded')
setTimeout(() => {screenshot.src = "dist/images/new-screenshot-2.jpeg"
}, 4000);
}
if (screenshot.complete) {
loaded()
} else {
screenshot.addEventListener('load', loaded)
screenshot.addEventListener('error', function() {
console.log('error')
})
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我没记错的那样,您不需要
settimeout()
函数中的卷发括号。普通语法可能如下:如果这不起作用,请检查以外的方式,除了
.complete
以检查是否已加载。我从未见过也没有使用过它,但是这看起来像正确的用法,loaded()
函数应在加载页面时发射。另外,您可以将onload
属性连接到HTML文件中的body
标签等待图像加载。As I recall correctly, you don't need the curly braces in the
setTimeout()
function. Normal syntax could be as follows:If this doesn't work, then check to see if there is another way than
.complete
to check if it is loaded. I have never seen nor used it, but this looks like correct usage and theloaded()
function should fire when the page loads. Alternatively, you can hook up anonload
attribute to thebody
tag in the HTML file and set the value to'loaded'
or another function instead of waiting for the image to load.您正在寻找的是
onload
事件,您会这样使用它:What you are looking for is the
onload
event, you would use it like so: