如何防止滚动经常执行

时间:2014-01-01 20:19:21

标签: javascript jquery

我希望有一个功能,可以在第一次触摸时滚动我的孔部分。 为了清楚说明我的html:

<div id="page" class="page">
        <section class="section" id="main" data-title="Fa"> </section> <!-- // #main -->

        <section class="section" id="about" data-title="About"> </section> <!-- // #about -->

        <section class="section" id="services" data-title="Services"></section> <!-- // #services -->

        <section class="section" id="projects" data-title="Projects"> </section> <!-- // #projects -->

       <section class="section" id="contact" data-title="Contact"> </section> <!-- // #contact -->

我也有一个jsfiddle: http://jsfiddle.net/95r9Q/3/

我的js运行正常。但是,如果我向下滚动,它不会只向下一个部分。有时它不止一个。任何阻止它的想法?

这是我的JS:

var move = true;
function scrollPage(element) { 
        var offset = element.offset().top;        
        move = false;
        $('html, body').animate({scrollTop: offset}, 'slow',function(){
            console.log("done animate scrollPage");
            move = true;
            });
}
var loopBottom = true, loopTop  = true;
var moveSectionDown = function (){
           console.log("moveSectionDown executed");
            var next = $('.section.active').next('.section');
            //looping to the top if there's no more sections below
            if(loopBottom && !next.length){
                next = $('.section').first();
            }

            if (next.length > 0 || (!next.length && loopBottom)){
                scrollPage(next);
            }
};

$(window).scroll(function() {
    if (move){
          var currentScroll = $(window).scrollTop(); 
          var scrolledSections = $('.section').map(function(){
                    if ($(this).offset().top < (currentScroll + 100)){
                        return $(this);
                    }
          });
          //geting the last one, the current one on the screen
         var currentSection = scrolledSections[scrolledSections.length-1];

                if(!currentSection.hasClass('active')){

                    console.log("currentSection.hasClass('active') executed");
                    $('.section.active').removeClass('active');
                    currentSection.addClass('active');
                    var element = $('.section.active');
                    if(element.length){
                      console.log("element.active: ",element);
                           isScrolling = true;
                        moveSectionDown();
                       }
                }
  }// Ende move        

});

0 个答案:

没有答案