滚动DIV元素时如何防止页面滚动? [英] How to prevent page scrolling when scrolling a DIV element?

查看:94
本文介绍了滚动DIV元素时如何防止页面滚动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经审查并测试了防止人体在div内滚动的各种功能,并结合了应该起作用的功能.

I have reviewed and tested the various functions for preventing the body ability to scroll whilst inside a div and have combined a function that should work.

$('.scrollable').mouseenter(function() {
    $('body').bind('mousewheel DOMMouseScroll', function() {
        return false;
    });
    $(this).bind('mousewheel DOMMouseScroll', function() {
        return true;
    });
});
$('.scrollable').mouseleave(function() {
    $('body').bind('mousewheel DOMMouseScroll', function() {
        return true;
    });
});

  • 这将停止所有滚动,因为我希望在容器内仍可以滚动
  • 这同样不会在鼠标离开时停用
  • 有什么想法或更好的方法吗?

    Any ideas, or better ways of doing this?

    推荐答案

    更新2:我的解决方案基于完全禁用浏览器的本机滚动(当光标位于DIV内时),然后手动滚动使用JavaScript的DIV(通过设置其.scrollTop属性).另一种和IMO更好的方法是仅选择性地禁用浏览器的滚动,以防止页面滚动,而不是DIV滚动.在下面查看Rudie的答案,该答案演示了此解决方案.

    Update 2: My solution is based on disabling the browser's native scrolling altogether (when cursor is inside the DIV) and then manually scrolling the DIV with JavaScript (by setting its .scrollTop property). An alternative and IMO better approach would be to only selectively disable the browser's scrolling in order to prevent the page scroll, but not the DIV scroll. Check out Rudie's answer below which demonstrates this solution.

    您在这里:

    $( '.scrollable' ).on( 'mousewheel DOMMouseScroll', function ( e ) {
        var e0 = e.originalEvent,
            delta = e0.wheelDelta || -e0.detail;
    
        this.scrollTop += ( delta < 0 ? 1 : -1 ) * 30;
        e.preventDefault();
    });
    

    实时演示: https://jsbin.com/howojuq/edit?js,output

    因此,您可以手动设置滚动位置,然后阻止默认行为(即滚动DIV或整个网页).

    So you manually set the scroll position and then just prevent the default behavior (which would be to scroll the DIV or whole web-page).

    更新1:如Chris在下面的注释中所述,在jQuery的较新版本中,增量信息嵌套在.originalEvent对象中,即jQuery不在其自定义Event对象中公开它.不再,我们必须从本地Event对象中检索它.

    Update 1: As Chris noted in the comments below, in newer versions of jQuery, the delta information is nested within the .originalEvent object, i.e. jQuery does not expose it in its custom Event object anymore and we have to retrieve it from the native Event object instead.

    这篇关于滚动DIV元素时如何防止页面滚动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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