我在网页上有一张图片,它是由服务器端 CGI 程序动态生成的。此图像由计时器定期刷新和/或根据用户输入进行更改。所以我有一个 JavaScript 函数,比如
// <img id="screen" src=""> is elsewhere in the page
function reloadImage() {
$("#screen").attr("src", make_cgi_url_based_on_form_inputs());
}
这工作得很好,但有时加载图像需要一段时间。因此,我希望出现某种消息,内容为“正在加载图像...”,但当图像已加载并显示在浏览器中时,该图像就会消失。
是否有任何类型的 JavaScript 事件可以做到这一点?或者,有没有其他方法可以通过 Ajax 或其他方式加载/更改/更新图像并检测加载何时完成?
最佳答案
您可以试试这个 jquery 解决方案:http://jqueryfordesigners.com/image-loading/
$(function () {
var img = new Image();
$(img).load(function () {
//$(this).css('display', 'none'); // .hide() doesn't work in Safari when the element isn't on the DOM already
$(this).hide();
$('#loader').removeClass('loading').append(this);
$(this).fadeIn();
}).error(function () {
// notify the user that the image could not be loaded
}).attr('src', 'http://farm3.static.flickr.com/2405/2238919394_4c9b5aa921_o.jpg');
});
关于javascript - 检测特定图像何时完成加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1379994/