Get height of image inside a hidden div

前端 未结 9 581
自闭症患者
自闭症患者 2021-01-02 18:50

i want to to get the height/width of an image inside a hidden div-containter, but .height() and .width() both returns 0 (like expected).

         


        
相关标签:
9条回答
  • 2021-01-02 19:02

    Make the div temporarily visible in order to compute the height or hide the div off screen instead of using display: None. I have used the first approach, and found it to be fast enough that you will never see the element.

    0 讨论(0)
  • 2021-01-02 19:02

    I'm not sure you can do it with jQuery (or javascript at all). I had a similar problem with misreported heights and widths on loading/hidden img's. You can, however, wait till the image loads, get it's correct height and width and then hide the parent... like so:

    var height, width;
    
    $('#myimg').load(function() {
        height = $(this).height();
        width = $(this).width();
        $('#init').hide();
    }
    
    0 讨论(0)
  • 2021-01-02 19:16

    Yes its because the image is not loaded yet and this is my solution:

    $('<img src="My Image URL" />').appendTo('body').css({
                    'position': 'absolute',
                    'top': -1
                }).load(function() {
                    console.log('Image width: ' + $(this).width());
                    console.log('Image height: ' + $(this).height());
                    $(this).remove();
                });
    
    0 讨论(0)
提交回复
热议问题