【问题标题】:Jquery function to vertical align the elements doesn't work用于垂直对齐元素的 Jquery 函数不起作用
【发布时间】:2017-01-21 06:28:04
【问题描述】:

我正在使用此功能垂直对齐以下link中有关项目的信息:

/* First make each project-section div full height */   
$(window).on("load resize scroll", function(e) {
    if ($(window).height() > 600 && $(window).width() > 980 ) {
        screenHeight = $(window).height();
        menuHeight = $('#main-header').outerHeight();
        finalHeight = screenHeight - menuHeight;
        $('.project-section').css('height', finalHeight + 'px');

        /* Then Vertically align the elements */
        var colHeightElement = $('.project-section > .et_pb_row > .et_pb_column');
        colHeightElement.each(function( index ) {
            var colHeight = $(this).outerHeight();
            var colPadding = (finalHeight-colHeight)/2;
            $(this).css('padding-top', colPadding + 'px');
        });

    }


});

正如您在链接中看到的,元素永远不会得到正确的高度,但我找不到原因。

【问题讨论】:

    标签: jquery vertical-alignment


    【解决方案1】:

    我认为问题出在滚动功能上。用户第一次滚动时,它需要 padding-top 0,但是当它继续滚动时,它需要 .outerheight() 和给定的填充并重新计算值。

    解决办法是改变这个:

    var colHeight = $(this).outerHeight();
    

    到这里:

    var colHeight = $(this).height();
    

    【讨论】:

      【解决方案2】:

      jQuery 不需要让你的 div 垂直居中 - 你可以使用 plan CSS 来做到这一点。

      我在检查元素中看到,您的每一列都获得了某个值的填充顶部。我猜这来自你的 jQuery 脚本:

      /* Then Vertically align the elements */
      var colHeightElement = $('.project-section > .et_pb_row > .et_pb_column');
      colHeightElement.each(function( index ) {
          var colHeight = $(this).outerHeight();
          var colPadding = (finalHeight-colHeight)/2;
          $(this).css('padding-top', colPadding + 'px');
      });
      

      删除该代码块并确保.et_pb_column 没有任何填充或边距。

      之后,添加以下代码:

      .project-section .et_pb_row {
          padding-top: 0;
          padding-bottom: 0;
          margin-top: 0;
          margin-bottom: 0;
      
          /* This will center your div vertically */
          height: 100%;
          display: flex;
          align-items: center;
      }
      

      【讨论】:

      • 这可能是一个解决方案,但是我真的很想知道如何使用jquery解决它,因为我将来会扩展该功能并且因为flex-box在IE上没有很好的支持
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-04
      • 2017-05-29
      • 1970-01-01
      • 2020-03-19
      相关资源
      最近更新 更多