2012-04-13 89 views
2

我的腳本的目標是,當用戶向下滾動時,我的頁面應滾動到下一個div。爲此,該腳本區分用戶是否上下滾動。之後,當他滾動時,它應該刪除我的第一個div的類active,並添加到下一個。然後它滾動到類active的新分區。問題在於,它僅適用於第一次滾動,而不是下一次。jQuery - 滾動事件

我的代碼:

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

我找到了答案

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(); 
})​ 
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; 
}); 
}); 

修訂 我增加了$當前VAR到滾動功能以及。

+0

謝謝,但是當我這樣做,我的卷軸變得瘋狂。它正在向下和向上滾動。 – 2012-04-13 15:36:52

+0

忘了把$ current變量放在那裏。再試一次。 – Lee 2012-04-13 15:39:19

+0

瘋狂=第一次滾動後上下跳。 $ .scrollTo來自插件jquery ScrollTo。它正在使用滾動到我的課活躍。你可以看到這裏發生了什麼:http://anthonykim.fr/stack/test5.html – 2012-04-13 15:44:28