Javascript 完整图像加载后的javascript执行功能

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4100252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:36:32  来源:igfitidea点击:

javascript executing function after full image load

javascriptimagecallbackload

提问by kalpaitch

I have the following line of javascritp $("#hero_image img").attr('src', src);to change an image. The following lines then do whatever they do based on the images new width which I was calling through $("#hero_image img").width();.

我有以下一行 javascritp$("#hero_image img").attr('src', src);来更改图像。下面几行然后根据我通过$("#hero_image img").width();.

However, how do I ensure that this image has fully loaded before getting the width, otherwise I will be returned with the old width? Setting a timeout isn't reliable enough.

但是,如何在获取宽度之前确保此图像已完全加载,否则将返回旧宽度?设置超时不够可靠。

回答by Nick Craver

You can get the width in the .load()event handler which fires after it's fully loaded, like this:

您可以在.load()完全加载后触发的事件处理程序中获取宽度,如下所示:

$("#hero_image img").load(function() {
  alert($(this).width());
}).attr('src', src);

If you're doing this and re-using the image, either bind the .load()handler once, of you need different behavior each time use .one()so it doesn't keep addingan onloadevent handler:

如果你这样做,并重新使用的图像,无论是绑定的.load()处理程序一次,你需要不同的行为,每一次使用.one(),因此不会继续增加onload事件处理程序:

$("#hero_image img").one('load', function() {
  alert($(this).width());
}).attr('src', src);

回答by Josiah Ruddell

$(function(){ // document ready
    $('#hero_image img').bind('load', function(){ // image ready
        // do stuff here
    });
});