我的脚本的目标是当用户向下滚动时,我的页面应该滚动到下一个div。为此,脚本区分用户是否向上和向下滚动。之后,当他滚动时,它应该删除我的第一个div的类active
并添加到下一个。然后它用类active
滚动到新的div。问题是它只适用于第一个滚动而不适用于下一个滚动。
我的代码:
$(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;
});
});
有人能帮助我吗?
答案 0 :(得分: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添加到了scroll函数中。
答案 1 :(得分: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();
})