How to get the height of a hidden image?

前端 未结 5 1985
陌清茗
陌清茗 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); });
    
    0 讨论(0)
  • 2021-01-20 06:05

    Check out this thread.

    Don't load hidden images

    0 讨论(0)
  • 2021-01-20 06:09

    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.

    0 讨论(0)
  • 2021-01-20 06:22

    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>
    
    0 讨论(0)
  • 2021-01-20 06:26

    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.

    0 讨论(0)
提交回复
热议问题