Jquery.height()使用F5或CTRL + F5返回不同的结果

时间:2012-11-09 18:44:50

标签: javascript jquery

所以我试图找到我的图像的高度,然后添加一个上边距,这使我能够施加一个垂直中心。

我正在运行此代码,并且在 F5刷新上我获得了正确的高度,但在 CTRL + F5刷新时,它给了我一个更小的高度。我有点假设这是一个加载/延迟的东西,但我正在使用文档准备好所以不确定最新情况。我尝试使用php函数,但它让网站速度惊人,所以必须坚持使用jquery。

你可以看到它在这里工作。 www.mzillustration.com

 jQuery(document).ready(function() {

 if (jQuery('.imagedisplay').length != 0) {
                jQuery('.imagedisplay').each(function(){ 

                var imgheight = jQuery(this).find('img').height();

                var topmarg = ((240 - imgheight) / 2) ; 

                jQuery(this).find('img').css({'margin-top':topmarg+'px'});



            });

});

任何想法/帮助/解释非常感谢。 感谢

5 个答案:

答案 0 :(得分:7)

onload和onready之间存在差异。

ready将等到实际的DOM树完成,而onload将等待,直到页面上显示的所有内容都完成加载。因此,一个解释是,当清除缓存并刷新时,dom树的完成速度比图像快得多,因此给出了错误的高度。

尝试使用onload-event,看看你是否得到了不同的结果。

答案 1 :(得分:3)

在询问浏览器的高度之前,您需要确保图像已加载。如果该图像路径存在于html中,那么您将不幸需要一个jquery插件来以跨浏览器的方式处理它。

https://github.com/alexanderdickson/waitForImages

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

或者你必须等待在jquery中看起来像这样的window.onload事件:

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

但是,如果您使用窗口加载事件,它将等到所有资源都已加载,并且与仅测量图像本身相比,取决于您的站点,这可能是一个严重的延迟。

或者,如果您对从javascript加载图像感到满意,只需正确排序代码即可:

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

您看到重新加载页面的方式有所不同的原因是,简单的刷新不会清除缓存,因此图像已经加载。当你点击ctrl + f5时它会清除缓存,所以当你向浏览器询问高度时,图像还没有被加载。

对于开发期间的缓存控制,请考虑使用firefox Web开发人员工具栏。

enter image description here

答案 2 :(得分:1)

尝试这种方法:

jQuery(function() {
    jQuery('.imagedisplay img').each(function() {
        var $this   = jQuery(this),
            height  = $this.height();
        if (height) {
            $this.css('margin-top', ((240 - height) / 2) + 'px');
        } else {
            $this.on('load', function() {
                $this.css('margin-top', ((240 - $this.height()) / 2) + 'px');
            });
        }
    });
});

答案 3 :(得分:0)

图像可以/可以与实际页面内容分开地高速缓存/加载。准备好的文件可以(并且根据我的经验)在加载所有内容之前发生。

尝试向正在加载的实际元素添加事件侦听器。

答案 4 :(得分:0)

在提取高度之前,您需要确保已加载图像。您可以使用图片上的complete属性轻松进行检查。试试这个:

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
});
相关问题