javascript executing function after full image load [duplicate]

谁说我不能喝 提交于 2019-11-27 03:52:50

问题


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();.

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.


回答1:


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

$("#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 adding an onload event handler:

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



回答2:


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


来源:https://stackoverflow.com/questions/4100252/javascript-executing-function-after-full-image-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!