[removed] scroll from one div to the other when scrolling?

后端 未结 1 917
故里飘歌
故里飘歌 2021-01-05 02:41

I want to be able, when scrolling down, to go directly to the next div, and when scrolling up, to go directly to the previous div. Here are my files with an example with two

相关标签:
1条回答
  • 2021-01-05 03:40

    scrollTo is a class to add to the divs you need to scroll to:

    <div id="black_hole" class="scrollTo">
    
    </div>
    <div id="space_od" class="scrollTo">
    
    </div>
    

    Js

    var scrolling = false;
    var currentPos = 0;
    
        function scrollUp(){
            if(!scrolling && currentPos > 0 ){
                scrolling=true;
                currentPos --;
                var scrollToElement = $('.scrollTo')[currentPos];
    
                $('html, body').animate({
                    scrollTop: $(scrollToElement).offset().top
                }, 500, function(){
                    scrolling = false;
                });      
            }
        }   
    
        function scrollDown(){   
            if(!scrolling && currentPos < $('.scrollTo').length-1  ){
                scrolling=true;
                currentPos ++;
                var scrollToElement = $('.scrollTo')[currentPos];
    
                $('html, body').animate({
                    scrollTop: $(scrollToElement).offset().top
                }, 500,function(){
                    scrolling = false;
                }); 
            }
        }    
    
        $(document).ready(function() {
    
            // Get the current position on load
    
            for( var i = 0; i < $('.scrollTo').length; i++){
                var elm = $('.scrollTo')[i];
    
                if( $(document).scrollTop() >= $(elm).offset().top ){
                    currentPos = i;
                }
            }
    
            $(document).bind('DOMMouseScroll', function(e){
                if(e.originalEvent.detail > 0) {
                    scrollDown();
                }else {
                    scrollUp();   
                }
                return false;
            });
    
            $(document).bind('mousewheel', function(e){
                if(e.originalEvent.wheelDelta < 0) {
                    scrollDown();
                }else {
                    scrollUp();     
                }
                return false;
            });
        });
    
    0 讨论(0)
提交回复
热议问题