gpt4 book ai didi

javascript - 在 Javascript 中预加载图像

转载 作者:行者123 更新时间:2023-11-29 10:21:35 26 4
gpt4 key购买 nike

我创建了一个简单的照片库查看器,我想在后台预加载图像,然后在完成后运行一个函数。

我的问题是,我该怎么做?

最佳答案

var image = new Image();
image.src = "http://foo.com/myimage.jpg";

//if you have a div on the page that's waiting for this image...
var div = getElementById("imageWrapperDiv");

//you can set it on the image object as the item to draw into...
image.myDiv = div;

image.onload = function(){
//do whatever you're going to do to display the image

//so in this example, because I have set this objects myDiv property to a div on the page
// I can then just populate that div with an img tag.
//it's not the most elegant solution, but you get the idea and can improve upon it easily
this.myDiv.innerHTML = "<img src='" + this.src +"'>";
}

一旦图像加载,它就会在浏览器的缓存中,因此,如果您使用 src 属性,您可以在页面上的任何位置绘制它,它会立即显示。

关于javascript - 在 Javascript 中预加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10726289/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com