gpt4 book ai didi

javascript - 鼠标滚轮在容器内滚动 - 捕捉事件

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:05:18 24 4
gpt4 key购买 nike

我有一个带有内部可滚动 DIV 的页面。当我将鼠标悬停在它上面并尝试用鼠标滚轮滚动它时,该 DIV 的内容根据需要滚动,而主页保持不变。但是当我到达 DIV 滚动区域的底部时,整个页面开始滚动。

我已经尝试在那个 div 上设置事件处理程序,但是 preventDefault() 方法也阻止了 DIV 本身的滚动。

错误代码如下:

$('.folderlist').on('DOMMouseScroll mousewheel', function(ev){
ev.stopPropagation();
ev.preventDefault();
})

preventDefault() 防止页面滚动,但也不允许 DIV 滚动。

stopPropagation() 我想在这种情况下什么都不做

我错过了什么吗?..

最佳答案

andbeyond 提出了一个很好的解决方案,尽管它在 IE 上存在问题,所以我已经尝试修复这些问题,现在就开始吧:

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);
}
});
});
}
});

现在它完全符合我的要求。感谢 andbeyond 的精彩博文 - http://www.andbeyonddesign.com/Blog/2012/02/Setting-scroll-only-for-scrollable-div

示例用法:$('.folderlist').scrollStop(true);

关于javascript - 鼠标滚轮在容器内滚动 - 捕捉事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9977628/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com