如何获得隐藏图像的高度? [英] How to get the height of a hidden image?

查看:128
本文介绍了如何获得隐藏图像的高度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当div被隐藏( display:none )时,浏览器将不会加载其中的图像。 有没有办法告诉浏览器加载图像?我需要图像的高度和宽度进行一些预处理。

When a div is hidden (display:none) the browser will not load the images that are inside it. Is there a way to tell the browser to load the image? I need the height and the width of the image to do some pre-processing.

注意:由于某些其他代码,我不能使div可见。 查看此处的示例
另外一个懒加载的例子对我来说不行。

Note: due to some other code, I can't make the div visible. Check the example here. Also a "lazy load" example wouldn't work for me.

推荐答案

我已经添加了一些预加载,将它包装成一个函数,这样做的诀窍:

I've added some preloading, wrapped it into a function and that does the trick:

function getImageDimension(el, onReady) {    
    var src = typeof el.attr === 'function' ? el.attr('src') : el.src !== undefined ? el.src : el;

    var image = new Image();
    image.onload = function(){
        if(typeof(onReady) == 'function') {
            onReady({
                width: image.width,
                height: image.height
            });
        }
    };
    image.src = src;
}

可以用作:

getImageDimension($('#img1'), function(d){ alert(d.height); });
var url = 'http://urology.jhu.edu/patrickwalsh/photo1.jpg';
getImageDimension(url, function(d){ alert(d.height); });

这篇关于如何获得隐藏图像的高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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