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

后端 未结 5 2113
心在旅途
心在旅途 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:00

    You need to insure the image has loaded before asking the browser for its height. If that image path is living in the html you will unfortunately need a jquery pluggin to handle this in a cross browser manner.

    https://github.com/alexanderdickson/waitForImages

    http://desandro.github.com/imagesloaded/

    Or you will have to wait for the window.onload event which in jquery looks like this:

      $(window).on('load', function(){....
    

    However if you use the window load event, it will wait until ALL resources have loaded and depending on your site that can be a serious delay when compared to measuring just the image itself.

    Or if you are comfortable with loading the image from javascript, simply ordering your code properly will handle this:

     var loadTester = new Image(),
         imgH;
     $(loadTest).on('load',function(){
         imgH = $('#image').attr('src',loadTester.src).height();
     }
     loadTester.src = "paht/to/image.jpg";
    

    The reason you are seeing a difference in the manner you reload the page, is that a simple refresh does not clear the cache, so the image is already loaded. When you hit ctrl+f5 it clears the cache and so the image is not yet loaded when you ask the browser for the height.

    For cache control durring development consider getting the firefox web-developer toolbar.

    enter image description here

提交回复
热议问题