当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Mousewheel scrolling inside container - catching events

问题描述:

I have a page with inner scrollable DIV. As I hover a mouse over it and try to scroll it with mouse wheel, the contents of that DIV is scrolled as desired while the main page stays put. But when I reach the bottom of the DIV's scrolling area, whole page begin to scroll instead.

I've tried to set event handlers on that div, but preventDefault() method also prevents scrolling of the DIV itself.

Here comes the wrong code:

$('.folderlist').on('DOMMouseScroll mousewheel', function(ev){

ev.stopPropagation();

ev.preventDefault();

})

preventDefault() prevents page scroll, but also disallows the scrolling of the DIV.

stopPropagation() does nothing in this case, I suppose

Did I miss something?..

网友答案:

andbeyond came up with a nice solution, though it had issues with IE so I've tried to fix them and here you go:

function stopEvent(e) {
    e = e ? e : window.event;
    if (e.stopPropagation) e.stopPropagation();
    if (e.preventDefault) e.preventDefault();
    e.cancelBubble = true;
    e.cancel = true;
    e.returnValue = false;
    return false;
}

$.fn.extend({
    // param: (boolean) onlyWhenScrollbarVisible
    // If set to true, target container will not intercept mouse wheel
    //     event if it doesn't have its own scrollbar, i.e. if there is too
    //     few content in it. I prefer to use it, because if user don't see
    //     any scrollable content on a page, he don't expect mouse wheel to
    //     stop working somewhere.

    scrollStop: function(onlyWhenScrollbarVisible) {
        return this.each(function(){
            $(this).on('mousewheel DOMMouseScroll', function(e) {
                if (onlyWhenScrollbarVisible && this.scrollHeight <= this.offsetHeight)
                    return;

                e = e.originalEvent;
                var delta = (e.wheelDelta) ? -e.wheelDelta : e.detail;
                var isIE = Math.abs(delta) >= 120;
                var scrollPending = isIE ? delta / 2 : 0;
                if (delta < 0 && (this.scrollTop + scrollPending) <= 0) {
                    this.scrollTop = 0;
                    stopEvent(e);
                }
                else if (delta > 0 && (this.scrollTop + scrollPending >= (this.scrollHeight - this.offsetHeight))) {
                    this.scrollTop = this.scrollHeight - this.offsetHeight;
                    stopEvent(e);
                }
            });
        });
    }
});

Now it does exactly what I wanted. Thanks andbeyond for your great blog post - http://www.andbeyonddesign.com/Blog/2012/02/Setting-scroll-only-for-scrollable-div

Example usage: $('.folderlist').scrollStop(true);

网友答案:
$('.folderlist').hover(function (){
    $('body').css('overflow','hidden');
}, function (){
    $('body').css('overflow','auto');
})

try that .. guess it should work

分享给朋友:
您可能感兴趣的文章:
随机阅读: