Mousewheel scrolling inside container - catching events

耗尽温柔 提交于 2019-12-05 12:40:25

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!