2012-03-20 86 views
0

我想知道當用戶滾動過某個點時,像Facebook這樣的網站如何使用它們的時間軸功能浮動某個元素(通常是菜單欄或有時是社交插件等)的元素不在屏幕上等。滾動上的浮動元素

當用戶滾動到某個元素或向下滾動一定數量的像素時,可以將其視爲更一般的JavaScript(jQuery?)事件觸發。

很顯然,這將需要從切換CSS屬性:

#foo { position: relative; } 

#foo { position: fixed; } 

或者使用jQuery,是這樣的:

$('#foo').css('position', 'fixed'); 

另一種方式,我已經看到了這一點實現是與博客,其中一個彈出窗口將被稱爲當你到達底部,或靠近頁面的底部。我的問題是,什麼是解僱代碼,並且可以鏈接或提供一些語法/語義/示例?

編輯:我看到一些很棒的JS變體出現,但是當我使用jQuery時,我認爲插件提到會很好。

回答

0

看看這個的jsfiddle:http://jsfiddle.net/remibreton/RWJhM/2/

在這個例子中,我使用document.onscroll = function(){ //Scroll event }檢測文檔上的滾動事件。

然後我計算基於它的高度滾動頁面的百分比。 (document.body.scrollTop * 100/(document.body.clientHeight - document.documentElement.clientHeight))

document.body.scrollTop是從頂部滾動的像素的數量,document.body.clientHeight是整個文檔的高度,而document.documentElement.clientHeight是文檔的可見部分,也稱爲視口。

然後您可以將此值與目標百分比進行比較,執行JavaScriptif(currentPercentage > targetPercentage) ...

這裏的整個事情:

document.onscroll = function(){ 
     var targetPercentage = 80; 
     var currentPercentage = (document.body.scrollTop * 100/(document.body.clientHeight - document.documentElement.clientHeight)); 
     console.log(currentPercentage); 
     if(currentPercentage > targetPercentage){ 
      document.getElementById('pop').style.display = 'block'; 
      // Scrolled more than 80% 
     } else { 
      document.getElementById('pop').style.display = 'none'; 
      // Scrolled less than 80% 
     } 
    } 

如果你喜歡的jQuery,這裏是相同的例子翻譯成大家的喜愛的圖書館:http://jsfiddle.net/remibreton/8NVS6/1/

$(document).on('scroll', function(){ 
    var targetPercentage = 80; 
    var currentPercentage = $(document).scrollTop() * 100/($(document).height() - $(window).height()); 
    if(currentPercentage > targetPercentage){ 
     $('#pop').css({display:'block'}); 
     //Scrolled more than 80% 
    } else { 
     $('#pop').css({display:'none'}); 
     //Scrolled less than 80% 
    } 
});​ 
0

我剛纔已經回答基本同樣的問題here。在這種情況下,它是一個表,它的頭,以及其基本思路是這樣的:

function placeHeader(){ 
    var $table = $('#table'); 
    var $header = $('#header'); 
    if ($table.offset().top <= $(window).scrollTop()) { 
     $header.offset({top: $(window).scrollTop()}); 
    } else { 
     $header.offset({top: $table.offset().top}); 
    }  
} 

$(window).scroll(placeHeader); 

Here's a demo

引用自己:

換句話說,如果表的頂部是scrollTop的上面,然後 位置scrollTop的報頭,否則把它放回在 表的頂部。根據網站其他部分的內容,您可能還需要檢查您是否已滾動瀏覽 表,因爲您不希望標題保持可見。

要回答你的問題直接,它是通​​過檢查scrollTop對元素的任何位置,或the height of the documentminusthe height of the viewport(用於滾動底部用的情況下)觸發。每次滾動事件觸發時都會執行此檢查(使用$(window).scroll(...)限制)。