2

我需要实现平滑的整页滚动。我已经在这个页面上做到了:

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);
    });
});
4

2 回答 2

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 );
于 2016-02-03T17:23:53.297 回答
0

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

  1. 定义最大页数 (fe) 10 页。
  2. 您可以选择实际页面,从 1 开始(不是 0 以方便编码)
  3. 禁用正常滚动。
  4. 当调用滚动并且目标不扩展最大页面并减少最小页面时(不进入#0页面) - 滚动
  5. 动态检测窗口调整大小。
  6. 祝你今天过得愉快。

  7. 如果你想在特定元素上滚动 - 我推荐你这个

注意:将 setInterval(f, 1000/60) 用于将用户带到 clientHeight 和实际页面相乘的动画。

于 2016-02-03T17:25:12.440 回答