How to get the height of a hidden image?

前端 未结 5 1986
陌清茗
陌清茗 2021-01-20 05:29

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?

5条回答
  •  不思量自难忘°
    2021-01-20 06:05

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

    Can be used as:

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

提交回复
热议问题