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

查看:114
本文介绍了完整图片加载后的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() ,因此它不会保留 em> 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天全站免登陆