阻止scrollTop调用scroll事件 [英] Prevent scrollTop from calling scroll event

查看:409
本文介绍了阻止scrollTop调用scroll事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建此行为:当用户滚动鼠标滚轮(或按)时,网页会向下滚动窗口的高度。

I'm trying to create this behavior: when user scrolls a mousewheel (or presses ) the webpage is scrolled down by the height of the window.

我最终得到以下代码:

var newScrollTop,
    oldScrollTop = $(window).scrollTop(),
    preventScroll = false;
$(window).scroll(function() {
    if (!preventScroll) {
        preventScroll = true;
        newScrollTop = $(this).scrollTop();
        if (newScrollTop > oldScrollTop) {
            $(this).scrollTop( oldScrollTop + $(window).height() );
        }
        else {
            $(this).scrollTop( oldScrollTop - $(window).height() );
        }
        oldScrollTop = newScrollTop;
        preventScroll = false;
    }
});

但是这不能像我预期的那样工作:滚动事件页面滚动到最边缘(底部或顶部)。我缺少什么?

But this doesn't work as I expect it: on scroll event page is scrolled to the very edge (bottom or top). What am I missing?

推荐答案

没有简单的方法来覆盖默认的浏览器滚动功能。这是实现你想要的一种方式,但它需要Brandon Aaron的 jquery -mousewheel插件来管理鼠标滚轮:

There is no easy way of overriding the default browser scroll functionality. Here's one way of doing what you want, but it requires Brandon Aaron's jquery-mousewheel plugin to manage the mouse scrollwheel:

$(function() {
    // Ugly hack to disable browser scrolling (downside: hides scrollbar!!!)
    $('html').css('overflow', 'hidden');

    // Get viewport height by which to scroll (up or down)
    var viewportHeight = $(window).height();

    // Recache viewport height on browser resize
    $(window).on('resize', function() {
        viewportHeight = $(window).height();
    });

    // Scroll on mousewheel
    $('html').on('mousewheel', function(event, delta, deltaX, deltaY) {
        // scroll down
        if (deltaY < 0)
            window.scrollBy(0, viewportHeight);
        // scroll up
        else
            window.scrollBy(0, -viewportHeight);
    });

    // Disable document keypress event
    // which would scroll the content even with "overlow: hidden"
    $(document).on('keypress', function(){
        return false;
    });

    // Scroll on arrow up/down keys
    $(document).on('keydown', function(event){
        // arrow down key
        if (event.which == 40)
            window.scrollBy(0, viewportHeight);
        // arrow up key
        if (event.which == 38)
            window.scrollBy(0, -viewportHeight);
    });
});

这是小提琴来演示代码。这一切都很有效,除了我的解决方案有一个丑陋的缺点。 $('html')。css('overflow','hidden'); 正在删除浏览器滚动条。

Here's a fiddle to demo the code. It all works very well except there is one ugly drawback to my solution. The $('html').css('overflow', 'hidden'); is removing the browser scrollbar.

这篇关于阻止scrollTop调用scroll事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆