【问题标题】:Javascript/JQuery function not working on first page load. Then works on refreshJavascript/JQuery 函数在第一页加载时不起作用。然后刷新
【发布时间】:2015-06-18 16:36:15
【问题描述】:

我有一个 javascript 函数,它通过查找父 div 的高度和它自己的高度来垂直居中 div,然后设置正确的定位。

第一次加载页面时,此功能似乎不起作用,但每次刷新后都会起作用。我在 $(document).ready 的顶部调用这个函数...

有什么想法吗?

function positionCardText() {

  $('.copyIllustration').each(function(i){
    var containerHeight = $(this).parent().height();
    var illustrationHeight = $(this).height();
    $(this).css('top', ( containerHeight/2 ) - ( illustrationHeight/2 ) );
  });

};

【问题讨论】:

  • 您的 JavaScript 文件是在页面顶部还是底部?如果它位于顶部,则在调用 JS 代码时可能尚未创建 HTML 元素,然后在重新加载页面时从缓存中提取。

标签: javascript jquery function refresh document


【解决方案1】:

当 div 包含图像时 - 只要图像未加载,高度计算就会出错。

如果重新加载页面,图片已经缓存,高度可以正确计算。

如果是这个原因,您可以将大小添加到图像标签,或者在图像的加载回调中加载脚本。

【讨论】:

    【解决方案2】:

    试试这个

     $(document).ready(function(){
        function positionCardText() {
    
          $('.copyIllustration').each(function(i){
            var containerHeight = $(this).parent().height();
            var illustrationHeight = $(this).height();
            $(this).css('top', ( containerHeight/2 ) - ( illustrationHeight/2 ) );
          });
    
        };
    
        });
    

    【讨论】:

      猜你喜欢
      • 2021-11-24
      • 2014-03-22
      • 1970-01-01
      • 2013-01-03
      • 1970-01-01
      • 2016-08-15
      • 2011-10-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多