Prevent scrolling of parent container when scrolling in overflow:scroll container has reached its limits

StackOverflow https://stackoverflow.com/questions/22287431

  •  12-06-2023
  •  | 
  •  

문제

Simply put, i guess you all know the issue: you use your mousewheel (or trackpad gesture) to scroll inside a div that is set to overflow:scroll (or a setting to that effect). The moment you reach the end of the scrollable area, the scroll 'commands' are immediately sent to the parent container - the main window for instance.

This can be quite annoying and i wonder if there is a way to prevent it.

I created this jsFiddle to demonstrate the issue and provide a ground for experimentation.

The only idea that came to my mind was using preventDefault but since i am not a JS wizard, i don't see where or how i could apply that correctly.

도움이 되었습니까?

해결책 2

After extensive research and violent testing, i combined my results into a solution that serves my purpose perfectly.

The approach is simple

Instead of measuring scroll conditions (on scroll) from within a container, we simply replace the entire scroll functionality by writing our own scroll handler. That way we have complete control over what is happening, plus the scroll event cannot default (or bubble) to the outer container:

Meet greedyScroll v0.9b

$.fn.extend({
    greedyScroll: function(sensitivity) {
        return this.each(function() {
            $(this).bind('mousewheel DOMMouseScroll', function(evt) {
               var delta;
               if (evt.originalEvent) {
                  delta = -evt.originalEvent.wheelDelta || evt.originalEvent.detail;
               }
               if (delta !== null) {
                  evt.preventDefault();
                  if (evt.type === 'DOMMouseScroll') {
                     delta = delta * (sensitivity ? sensitivity : 20);
                  }
                  return $(this).scrollTop(delta + $(this).scrollTop());
               }
            });
        });
    }
});

Usage

HTML:

<div class="scrollWrapper"></div>

Javascript:

$('.scrollWrapper').greedyScroll(25);

I found a value of 20 works fine for sensitivity, but some may prefer higher or lower settings.

Disclaimer

I don't claim this works in anything other than Chrome, as this is what i exclusively made sure it works for.

Credits go almost entirely to the team who developed the plugin i linked to in one of the comments to Lokesh's answer.

Code improvements are always welcome.

다른 팁

This is not optimal but I bootstrap uses this for their modal windows.

FIDDLE

.overflowHidden {
    overflow:hidden !important;
}

$('#scrollable').hover(function () {
        console.log("hello");
        $('body').addClass('overflowHidden');
    }, function () {
        $('body').removeClass('overflowHidden');
    });
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top