How to get the height of a hidden image?

When the div is hidden ( display:none), the browser will not load the images inside it. Is there any way to tell the browser to load an image? I need image height and width for preprocessing.

Note: due to some other code, I cannot make the div visible. See an example here . Also, the lazy loading example will not work for me.

+3
source share
5 answers

I added some preload, wrapped it in a function, and performed 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;
}

It 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); });
+4
source

div , position: absolute;.

" " , node URL-, , , .

+4

jquery - SO:

jQuery

, .

+3

.

0

, , "display: none"

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

Also see this example (save as .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
source

Source: https://habr.com/ru/post/1788985/


All Articles