prevent Scroll “bubbling” from element to window

2019-01-04 09:29发布

I have a modal box window (pop-up) that contains an iframe,
and inside that iframe there's a div that is scrollable.

When I scroll the iframe's inner DIV, and it has reached its top or bottom limit,
the window of the browser itself starts to scroll. this is an unwanted behavior.

I've tried something like this, which kills the main window scroll when
onMouseEnter when mouse enters pop-up box area:

e.preventDefault() is not working as it should for some reason...

$("#popup").mouseenter(function(){
   $(window).bind("scroll", function(e){
        e.preventDefault();
   }); 
}).mouseleave(function(){
    $(window).unbind("scroll");
});

Update

Seems like now in 2013 e.preventDefault(); is enough...

13条回答
唯我独甜
2楼-- · 2019-01-04 10:15

Sorry, as far as I'm aware it is impossible to cancel any kind of scroll event.

Both W3 and MSDN say:

Cancelable  No
Bubbles     No

I think you'll have to leave this up to browser authors to fix. Firefox (3.5 on Linux, anyway) seems to have a better behaviour for me: it only scrolls the parent if the child is already at the top/bottom end at the moment you start using the scrollwheel.

查看更多
等我变得足够好
3楼-- · 2019-01-04 10:21

Apparently, you can set overflow:hidden to prevent scrolling. Not sure how that'd go if the doc is already scrolled. I'm also on a mouseless laptop, so no scrolly wheel testing for me tonight :-) It's probably worth a shot though.

查看更多
劫难
4楼-- · 2019-01-04 10:27

my jQuery plugin:

$('.child').dontScrollParent();

$.fn.dontScrollParent = function()
{
    this.bind('mousewheel DOMMouseScroll',function(e)
    {
        var delta = e.originalEvent.wheelDelta || -e.originalEvent.detail;

        if (delta > 0 && $(this).scrollTop() <= 0)
            return false;
        if (delta < 0 && $(this).scrollTop() >= this.scrollHeight - $(this).height())
            return false;

        return true;
    });
}
查看更多
放我归山
5楼-- · 2019-01-04 10:27

you can try jscroll pane inside the iframe to replace the default scroll.

http://www.kelvinluck.com/assets/jquery/jScrollPane/jScrollPane.html

I am not sure, but give it a try

查看更多
放我归山
6楼-- · 2019-01-04 10:28

As of now in 2018 and onward e.preventDefault is enough.

$('.elementClass').on("scroll", function(e){
    e.preventDefault();
 }); 

This will prevent scroll to parent.

查看更多
Deceive 欺骗
7楼-- · 2019-01-04 10:30
function stopPropogation(e)
{
    e = e || window.event;
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
    if (e.preventDefault) e.preventDefault();
}

This should work.

查看更多
登录 后发表回答