Get height of image inside a hidden div

前端 未结 9 580
自闭症患者
自闭症患者 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 18:53

    I had a similar problem. The thing is that if an image or div containing an image has style="display:none" then its css height=0. I found that the height() and width() functions gave the wrong values, eg 0! The solution for me was to ensure that the images have their attributes set so even if they are hidden the values are still accessible. So use:

    $('#testImg').attr('height') and $('#testImg').attr('width') to get the height and width of the image.

    0 讨论(0)
  • 2021-01-02 18:53

    it looks like you need to compute the height & width of an image. if so, you're thinking of it too hard.

    0 讨论(0)
  • 2021-01-02 18:57

    I just ran across the solution for this, what you do is instead of rely on jQuery to do this for you. Instead, get the javascript element and get the height off of the element itself, as follows:

    var img = hiddenDiv.children('img');
    
    var imgHeight = img.get(0).height;
    var imgWidth = img.get(0).width;
    

    The jQuery method get(0) allows us to get at the underlying DOM element and interestingly enough, the DOM element dimensions don't change.

    One note though, for performance reasons, you will want to cache the img.get(0) if you plan on using it more.

    jQuery get method documentation

    0 讨论(0)
  • 2021-01-02 18:59

    you have to use find()

    $('body').find('#myimg').width();
    

    or

    $('body').find('#myimg').attr("width");
    

    becouse you have appended it after the DOM was loaded

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

    Its because the image has not loaded yet.....

    $('body').append('<div id="init"><img id="myimg" src="something.png" /></div>');
    $('#init').hide();
    
    $('#myimg').bind("load",function(){
        alert(this.height) //works
    })​
    

    heres a test: http://jsfiddle.net/WMpSy/

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

    You can't hide it if you want the correct height and width, but you can move it such that it will be out of the screen, and thus effectively hidden. Try this:

    var hiddenDiv = $('<div id="init"><img id="myimg" src="someimage.png" /></div>').appendTo('body').css({
        'position': 'absolute',
        'top': -9999
    });
    
    var img = hiddenDiv.children('img');
    img.height();
    img.width();
    
    0 讨论(0)
提交回复
热议问题