2016-09-13 43 views
0

我使用這個功能來垂直對齊關於以下link項目的信息:jQuery函數垂直對齊的元素不起作用

/* 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'); 
     }); 

    } 


}); 

正如你可以在鏈接看到的元素不會得到適當的高度,但我找不到原因。

回答

0

我認爲這個問題是與滾動功能。用戶第一次滾動時需要使用padding-top 0,但是當它繼續滾動時,需要使用指定填充的.outerheight()並重新計算該值。

的解決方案是可以改變:

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

這樣:

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

沒有必要讓jQuery垂直居中div - 您可以使用CSS來實現。

我在inspect元素中看到每個列都會獲得某個值的填充頂部。我想,從你的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; 
} 
+0

這可能是一個解決方案,但我真的想知道如何使用jQuery解決這個問題,因爲我要去在未來擴展功能,因爲flex-box在IE上沒有很好的支持 –