How to enforce a “smooth scrolling” rule for mousewheel, jQuery?

后端 未结 7 1299
太阳男子
太阳男子 2020-12-08 11:18

How are you? My Question:

How can I control or specify the way a document scrolls to the position of desire described by either the mouse scrollwheel, an

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-08 11:21

    var $window              = $(window),
        scrollDistance   = 300,
        scrollSpeed      = 500,
        scrollEffect     = 'swing',
        scrollAmount     = 1,
        smoothScroll;
    
    if (! ('ontouchstart' in document.documentElement) && ! $('body').hasClass('modal-open')) {
    
            $window.on("mousewheel DOMMouseScroll", function (event) {
    
                event.preventDefault();
    
                if (smoothScroll) {
    
                    // Start scrolling while waiting for final scoll amount (user stopped wheeling)
                    if (scrollAmount == 1) {
                        var delta = event.originalEvent.wheelDelta / 120 || -event.originalEvent.detail / 3;
                        var finalScroll = $window.scrollTop() - parseInt(delta * (scrollDistance * scrollAmount));
    
                        $('html, body').stop().animate({ scrollTop: finalScroll }, scrollSpeed, scrollEffect);
                    }
    
                    // Increase scroll amount
                    scrollAmount++;
    
                    // Clear current timeout
                    clearTimeout(smoothScroll);
                }
    
                // Set animated scroll
                smoothScroll = setTimeout(function() {
    
                    var delta = event.originalEvent.wheelDelta / 120 || -event.originalEvent.detail / 3;
                    var scrollTop = $window.scrollTop();
                    var finalScroll = scrollTop - parseInt(delta * (scrollDistance * scrollAmount));
    
                    // Reset scroll amoount
                    scrollAmount = 1;
    
                    $('html, body').stop().animate({ scrollTop: finalScroll },
                        (scrollSpeed*scrollAmount),
                        scrollEffect
                    );
    
                    // Clear timeout holder
                    smoothScroll = null;
    
                }, 100);
    
            });
    }
    

提交回复
热议问题