我的页面加载后如何运行settimeout?

发布于 2025-02-01 04:10:38 字数 463 浏览 4 评论 0原文

我想在加载页面后运行一个超时功能以显示图像,但我不知道为什么它不运行。这是语法问题吗? 这是我的代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

长途伴 2025-02-08 04:10:38

我没记错的那样,您不需要settimeout()函数中的卷发括号。普通语法可能如下:

function loaded() {
    console.log('loaded')
    setTimeout(() => screenshot.src = "dist/images/new-screenshot-2.jpeg", 4000); 
}

如果这不起作用,请检查以外的方式,除了.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:

function loaded() {
    console.log('loaded')
    setTimeout(() => screenshot.src = "dist/images/new-screenshot-2.jpeg", 4000); 
}

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 the loaded() function should fire when the page loads. Alternatively, you can hook up an onload attribute to the body tag in the HTML file and set the value to 'loaded' or another function instead of waiting for the image to load.

素食主义者 2025-02-08 04:10:38

您正在寻找的是onload事件,您会这样使用它:

document.body.addEventListener("load", loaded);

What you are looking for is the onload event, you would use it like so:

document.body.addEventListener("load", loaded);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文