简体   繁体   English

Javascript / JQuery函数无法在首页加载中使用。 然后进行刷新

[英]Javascript/JQuery function not working on first page load. Then works on refresh

I have a javascript function that centers a div vertically by finding the height of the parent div and its own height, then sets the correct positioning. 我有一个javascript函数,可通过查找父div的高度及其自身的高度来使div垂直居中,然后设置正确的位置。

This function doesn't seem to work when the page is loaded for the very first time but works every time after you refresh. 第一次加载页面时,此功能似乎不起作用,但每次刷新后均起作用。 I call this function at the top of $(document).ready... 我在$(document).ready的顶部调用此函数。

Any ideas? 有任何想法吗?

function positionCardText() {

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

};

When the div contains an image - the height calculation is wrong as long the image is not loaded. 当div包含图像时-如果未加载图像,则高度计算错误。

If you reload the page the image is already cached and the height can be calculated properly. 如果重新加载页面,则图像已被缓存,并且可以正确计算高度。

If this causes the reason, you can either add the size to the image tag or you load the script on the load callback of the image. 如果这是原因,则可以将大小添加到图像标签,也可以将脚本加载到图像的加载回调中。

Try this 尝试这个

 $(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 ) );
      });

    };

    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM