全页滚动

时间:2016-02-03 16:46:38

标签: javascript jquery scroll smooth-scrolling debouncing

我需要实现流畅的整页滚动。我已经在这个页面上做过了:

http://superhostitel.cz/sluzby

但是当我用滚轮滚动更多时,它会滚动更多页面。请问,如何设置仅滚动一页?

我的代码:

  $(document).ready(function () {
    var divs = $('.service');
    var dir = 'up'; // wheel scroll direction
    var div = 0; // current div
    $(document.body).on('DOMMouseScroll mousewheel', function (e) {
        if (e.originalEvent.detail > 0 || e.originalEvent.wheelDelta < 0) {
            dir = 'down';
        } else {
            dir = 'up';
        }
        // find currently visible div :
        div = -1;
        divs.each(function(i){
            if (div<0 && ($(this).offset().top >= $(window).scrollTop())) {
                div = i;
            }
        });
        if (dir == 'up' && div > 0) {
            div--;
        }
        if (dir == 'down' && div < divs.length) {
            div++;
        }
        //console.log(div, dir, divs.length);
        $('html,body').stop().animate({
            scrollTop: divs.eq(div).offset().top
        }, 800);
        return false;
    });
    $(window).resize(function () {
        $('html,body').scrollTop(divs.eq(div).offset().top);
    });
});

2 个答案:

答案 0 :(得分:1)

使用警卫来防止你的处理程序一次运行一次,在启动函数时启动标志,在动画结束时重置它。

这些方面的某些内容应该有用(没有测试它,但你应该明白这一点):

var running = false;
var handler = function (e) {
    if (running) {
        return;
    }
    running = true;
    if (e.originalEvent.detail > 0 || e.originalEvent.wheelDelta < 0) {
        dir = 'down';
    } else {
        dir = 'up';
    }
    // find currently visible div :
    div = -1;
    divs.each(function(i){
        if (div<0 && ($(this).offset().top >= $(window).scrollTop())) {
            div = i;
        }
    });
    if (dir == 'up' && div > 0) {
        div--;
    }
    if (dir == 'down' && div < divs.length) {
        div++;
    }
    //console.log(div, dir, divs.length);
    $('html,body').stop().animate(
        { scrollTop: divs.eq(div).offset().top }, // properties
        800,                                      // duration
        "swing",                                  // easing (needed to use 4th argument)
        function(){ running = false; }            // animation complete callback
    );

    return false;
};

$(document.body).on('DOMMouseScroll mousewheel', handler );

答案 1 :(得分:0)

你可以用另一种方式做到:

  1. 定义最多页数(fe)10页。
  2. 您可以选择实际页面,从1开始(不是0表示舒适编码)
  3. 禁用正常滚动。
  4. 当调用滚动并且目标没有扩展最大页面并且下降最小页面(不输入#0页面)时 - 滚动
  5. 动态检测窗口调整大小。
  6. 祝你有个愉快的一天。

  7. 如果你想在特定元素上滚动一下 - 我建议你this

  8. 注意:使用setInterval(f,1000/60)表示用户将userHeight和实际页面相乘的动画。

相关问题