开发者

How to get the height of a hidden image?

开发者 https://www.devze.com 2023-02-08 04:17 出处:网络
When a div is hidden (display:none) the browser will not load the images that are inside it. Is the开发者_运维技巧re a way to tell the browser to load the image? I need the height and the width of the

When a div is hidden (display:none) the browser will not load the images that are inside it. Is the开发者_运维技巧re 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.

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.


Make the div visible, but position it outside the page with position: absolute;.

If your "other code" doesn't let you do this either, create a new image node with the same URL, position it outside the page, wait until it's loaded, read its height and destroy.


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


You could try pre-loading the images using jquery - check out this SO answer:

Preloading images with jQuery

This should pre-load them before you even decide to display them.


I believe this is only true for items whose parent is "display:none"

See this article on the matter http://dev.jquery.com/ticket/125

Also, see this example (save as an .html file)

<html>
<head>
<title>Example</title>



<script type="text/javascript">
    $(document).ready(function(){
        alert($("#target").height());
    });
</script>
</head>

<body>
  <div id="parent" style="display:none;">
    <div id="target" style="height:100px;display:block;">
        a
    </div>
</div>
</body>
</html>


Check out this thread.

Don't load hidden images

0

精彩评论

暂无评论...
验证码 换一张
取 消