Jquery.height() returns different results using F5 or CTRL+F5

后端 未结 5 2150
心在旅途
心在旅途 2021-01-22 10:40

So I am trying to find the height of my images then add a top margin this enables me to impose a a vertical center.

I\'m running this code, and on an F5 refresh<

5条回答
  •  無奈伤痛
    2021-01-22 11:01

    You need to make sure the image has loaded before extracting a height. You can easily check this using the complete property on the image. Try this:

    var setH = function() {
        $(this).css('margin-top', (240 - this.height) / 2);
    }
    $('.imagedisplay img').each(function() {
        if( this.complete ) {
            setH.call(this); // apply height straight away
            return;
        }
        $(this).load(setH); // apply height when the image has loaded
    });
    

提交回复
热议问题