2015-07-03 49 views
3

我想嘗試實現循環滾動頁面的效果。 我發現這個腳本,我已經做了一些更改,作爲滾動1px加載,以啓用循環。scoll loop div

我應該在div中應用這種效果......但我無法弄清楚如何改變代碼以使其工作。

它幫助打開包裝div內的循環?

感謝 A.

$(document).ready(function() { 
$('body').height(WRHeight + $(window).height()); 
$(window).scroll(function() { 
    if ($(window).scrollTop() >= ($('body').height() - $(window).height())) { 
     $(window).scrollTop(1); 
    } 
    else if ($(window).scrollTop() == 0) { 
     $(window).scrollTop($('body').height() - $(window).height() -1); 
    }  
}); 

loop div jsfiddle

回答

2

我已經重新實現腳本,並增加了一些意見,希望更清楚:

// Container element which has a scrollbar 
var $c = $("#container"); 

// Child element which is taller than the container 
var $e = $("#element"); 

// The point at which the page will loop when scrolling down 
var loopPoint = $e.height() - $c.height(); 

// Define a function which runs whenever the scroll position of $c changes 
$c.scroll(function() { 

    // If the new scroll position matches our loop point 
    if ($c.scrollTop() === loopPoint) { 
     // Scroll to (almost) the the top ('0' would be the top; we do this so we don't loop back again instantly) 
     $c.scrollTop(1); 
    } 

    // Otherwise, if the new scroll position = the top of the element 
    else if ($c.scrollTop() === 0) { 
     // Scroll to (almost) the bottom, we can use (our loop point - 1) 
     $c.scrollTop(loopPoint - 1); 
    } 
}); 

這裏有一個對的jsfiddle你:http://jsfiddle.net/cjmoran/2do67um8/

注意:我注意到,這種方法可能會在Chrome瀏覽器中點擊滾動,導致JSfiddle崩潰。可能有更好的方法來實現這一點,這樣就不會發生。在最新版本的Firefox中顯示工作正常,但那些是我測試的唯一瀏覽器。

+0

感謝您的幫助! 不幸的是,我試圖實現你的代碼,但它不工作.... http://jsfiddle.net/wg59cmxy/ – Andrea

+0

爲我工作:) –