完整图像加载后的javascript执行功能 [英] javascript executing function after full image load

查看:23
本文介绍了完整图像加载后的javascript执行功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下一行 javascritp $("#hero_image img").attr('src', src); 来更改图像.下面几行然后根据我通过 $("#hero_image img").width(); 调用的图像新宽度做任何事情.

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.

推荐答案

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

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

如果您这样做并重新使用图像,请绑定 .load() 处理程序一次,每次使用 .one 时都需要不同的行为() 所以它不会添加一个 onload 事件处理程序:

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

这篇关于完整图像加载后的javascript执行功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆