2

我的脚本的目标是当用户向下滚动时,我的页面应该滚动到下一个 div。为此,脚本会区分用户是否向上和向下滚动。之后,当他滚动时,它应该删除active我的第一个 div 的类并添加到下一个。然后它滚动到带有 class 的新 div active。问题是它只适用于第一个滚动,而不是下一个。

我的代码:

$(window).load(function() {
    var tempScrollTop, currentScrollTop = 0;
    var $current = $("#container > .active");
    var next = $('.active').next();
    var prev = $('.active').prev();

    $(window).scroll(function() {
        currentScrollTop = $(window).scrollTop();

        if (tempScrollTop < currentScrollTop) { //scrolling down 
            $current.removeClass('active').next().addClass('active'); 
            $.scrollTo(next, 1000);
        }
        else if (tempScrollTop > currentScrollTop ) { //scrolling up
            $current.removeClass('active').prev().addClass('active');
            $.scrollTo(prev, 1000);
        }

        tempScrollTop = currentScrollTop;
    }); 
});

有谁能够帮我?

4

2 回答 2

0

我找到了答案

var lastScrollTop = 0; var isDoingStuff = false;

$(document).scroll(function(event) {
    //abandon 
    if(isDoingStuff) { return; }

    if ($(this).scrollTop() > lastScrollTop) {
        //console.log('down');
        $('.active').removeClass('active').next('div').addClass('active');
        isDoingStuff = true;
        $('html,body').animate( {scrollTop: $('.active').offset().top }, 1000, function() {
            setTimeout(function() {isDoingStuff = false;}, 100);
            console.log('off');
        });
    } else {
        //console.log('up');
    }
    lastScrollTop = $(this).scrollTop();
})​
于 2012-04-19T09:11:21.547 回答
0

您需要将 next 和 prev 变量移动到滚动函数中

$(window).load(function(){

var tempScrollTop, currentScrollTop = 0;



$(window).scroll(function(){

currentScrollTop = $(window).scrollTop();
//you need to assign the $current, next and prev here so they get the current elements (not the ones that were set at the beginning
var $current = $("#container > .active");    
var next = $('.active').next();
var prev = $('.active').prev();    


if (tempScrollTop < currentScrollTop )//scrolling down
{
$current.removeClass('active').next().addClass('active');
$.scrollTo(next, 1000);
}
else if (tempScrollTop > currentScrollTop )//scrolling up

{
$current.removeClass('active').prev().addClass('active');
$.scrollTo(prev, 1000);
}
tempScrollTop = currentScrollTop;
});
});

更新 我也将 $current var 添加到滚动函数中。

于 2012-04-13T15:33:53.383 回答