2013-09-25 49 views
0

我想計算網站頁腳和側邊欄之間的距離(具有可變的margin-top屬性,因爲它是模仿一個固定位置元素。)如果兩個元素之間的距離小於X你Ÿ

在較小的分辨率下,側邊欄將在頁腳頂部滾動​​。爲了解決這個問題,我想隱藏側欄,當它從頁腳開始是X px時,然後在頁腳上方滾動X px時再次顯示它。

我試過下面的代碼(這是在窗口滾動功能),但這是返回一個負數&不按預期方式工作。

 distance = sidebar.offset().top - footer.offset().top; 

     console.log(distance); 

     if (distance > -500) { 
      sidebar.fadeOut('fast'); 
     } else { 
      sidebar.fadeIn('fast'); 
     } 

回答

1

試試這個。

$(window).scroll(function() { 
//changed order, now you won't get negative number 
distance = (footer.offset().top - footer.outerHeight()) - sidebar.offset().top; 

if(distance <= 50) // 50 or any distance you want 
sidebar.fadeOut(500); 
else 
sidebar.fadeIn(500); 

}); 

$(window).scroll()裏面增加了那個部分,這樣每次滾動時都會檢查它。

+0

看起來可以工作,但它看起來好像是在計算頁腳底部而不是頂部的距離。偏移不應該從元素的頂部開始? – tctc91

+0

我對此不太確定,但如果出現問題,我會編輯解決該問題的答案(通過減去頁腳的高度)。 – KBN

+0

完美,謝謝! – tctc91