图片在document.ready上没有宽度 [英] Image does not have width at document.ready

查看:139
本文介绍了图片在document.ready上没有宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我希望用来调整图像大小的函数:

I have a function that I wish to use to resize images:

http://jsfiddle.net/eUurB/

当我在document.ready上运行它时,它没有任何效果;返回的图像大小是'0'(您可能会注意到它在小提琴中起作用...我不确定是什么导致这种不一致的说实话,但在我的测试网站上它绝对是返回'0的高度和宽度'。

When I run it on document.ready, it has no effect; the image size returned is '0' (You may notice that it does work in the fiddle... I'm not sure what's causing this inconsistencty to be honest, but on my test site it's most definitely returning height and width of '0'.

这是预期的行为吗?如果是这样,我怎么能在图像有宽度时做一个简单的监听器?

Is this expected behaviour? If so, how could I make a simple listener for when images have width?

推荐答案

这是一种超安全的方法,不需要等待所有图像加载,并处理图像可能被高速缓存或完成加载的情况DOM准备就绪。

Here's an ultra-safe way to do it that doesn't require waiting for all the images to load, and takes care of situations where the image may be cached or finished loading before the DOM is ready.

$('#my_img').one('load',function(){
    resizeImgByArea('logo', 50);
})
  .filter(function(){
     return this.complete;
})
  .load();







  • .one('load',...)一旦调用它就会删除处理程序。你只需要它一次。


    • .one('load',...) removes the handler as soon as it is invoked. You only need it once.

      。 filter()将返回已加载的图像。如果没有,则不返回任何元素。

      .filter() will return the image if it was already loaded. If not, it returns no elements.

      .load()将手动调用处理程序。只有在图像已经加载时才会出现这种情况。

      .load() will manually invoke the handler. This will only occur if the image was already loaded.

      所以如果在DOM准备好之前预先加载了图像,我们将手动调用其 .load()处理程序。如果没有,它的处理程序将在加载时被调用。

      So if the image was preloaded before the DOM was ready, we'll invoke its .load() handler manually. If not, its handler will be invoked when it is loaded.

      这篇关于图片在document.ready上没有宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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