Scrolling child div scrolls the window, how do I stop that?

后端 未结 14 733
生来不讨喜
生来不讨喜 2020-11-30 18:03

I have a div, with a scroll bar, When it reaches the end, my page starts scrolling. Is there anyway I can stop this behavior ?

相关标签:
14条回答
  • 2020-11-30 19:09

    You can inactivate the scrolling of the whole page by doing something like this but display the scrollbar!

    <div onmouseover="document.body.style.overflow='hidden'; document.body.style.position='fixed';" onmouseout="document.body.style.overflow='auto'; document.body.style.position='relative';"></div>
    
    0 讨论(0)
  • 2020-11-30 19:09

    Based on ceed's answer, here is a version that allows nesting scroll guarded elements. Only the element the mouse is over will scroll, and it scrolls quite smoothly. This version is also re-entrant. It can be used multiple times on the same element and will correctly remove and reinstall the handlers.

    jQuery.fn.scrollGuard = function() {
        this
            .addClass('scroll-guarding')
            .off('.scrollGuard').on('mouseenter.scrollGuard', function() {
                var $g = $(this).parent().closest('.scroll-guarding');
                $g = $g.length ? $g : $(window);
                $g[0].myCst = $g.scrollTop();
                $g[0].myCsl = $g.scrollLeft();
                $g.off("scroll.prevent").on("scroll.prevent", function() {
                    $g.scrollTop($g[0].myCst);
                    $g.scrollLeft($g[0].myCsl);
                });
            })
            .on('mouseleave.scrollGuard', function() {
                var $g = $(this).parent().closest('.scroll-guarding');
                $g = $g.length ? $g : $(window);
                $g.off("scroll.prevent");
            });
    };
    

    One easy way to use is to add a class, such as scroll-guard, to all the elements in the page that you allow scrolling on. Then use $('.scroll-guard').scrollGuard() to guard them.

    0 讨论(0)
提交回复
热议问题