如何获取隐藏图像的高度?

Kee*_*ker 4 html javascript jquery dom image

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

注意:由于一些其他代码,我无法使 div 可见。检查这里的例子。另外,“延迟加载”示例对我来说不起作用。

Kee*_*ker 5

我添加了一些预加载,将其包装到一个函数中,这样就达到了目的:

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;
}
Run Code Online (Sandbox Code Playgroud)

可以用作:

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