div 内的滚动循环

scroll loop inside div

我想尝试实现一个循环滚动页面的效果。 我找到了这个脚本,我在滚动 1px 加载时对其进行了一些更改以启用循环。

我是否应该在 div 中应用此效果...但我不知道要更改代码以使其工作。

它有助于打开包装器内的循环 div?

$(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

我重新实现了脚本并添加了一些注释,希望能使它更清楚:

// 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 中运行良好,但这些是我测试过的唯一浏览器。