gpt4 book ai didi

javascript - 使用 onscroll 检测鼠标滚轮

转载 作者:行者123 更新时间:2023-12-03 11:16:22 27 4
gpt4 key购买 nike

我尝试了多种方法来准确检测 mousewheel/DOMMouseScroll 事件,但似乎不同浏览器的结果会有很大差异,尤其是硬件的差异到另一个硬件。 (例如:MacBook Magic Trackpad 会触发许多鼠标滚轮事件等)

JS 库已经多次尝试“规范化”mousewheel 事件的 wheelDelta。但其中许多都失败了(我不再找到相关的SO问题,但有一些指出了这个失败)。

这就是为什么我现在尝试一个mousewheel事件的解决方案,而是onscroll事件。 Here is an example使用滚动的隐藏容器 (#scroller) 和具有正常内容的普通容器 (#fixed_container) 进行滚动/鼠标滚轮检测。

由于#scroller的高度有限(此处为4000px),我无法检测到滚动/鼠标滚轮无限...

如何允许无限滚动事件(通过为#scroller设置无限高度?如何?)?

<小时/>

代码/Live demo :

<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<style>
body { overflow:hidden; }
#scroller { height: 4000px; }
#fixed_container { position:fixed; top:0px; left:0px; }
#text { position:absolute; top:100px; left:100px; }
</style>

<script type="text/javascript">
window.onscroll = function(e) {
console.log("scroll event detected! " + window.pageXOffset + " " + window.pageYOffset);
e.preventDefault();
return false;
}
</script>
</head>

<body>
<div id="scroller"></div>
<div id="fixed_container">
<div id="text">
Bonjour
</div>
</div>
</body>
</html>

最佳答案

“如何允许无限滚动事件”

这应该可以做到:

$(window).scroll(function() {
var st= $(window).scrollTop();
var wh= $(window).height();
var sh= $('#scroller').height();

if(sh < st+wh*2) {
$('#scroller').css({
height: st+wh*2
});
};
});

在 IE11、Firefox、Chrome、Opera 和 Safari 中进行了测试。

在下面的 fiddle 中,单击添加文本,以便您可以看到它滚动:

Fiddle

关于javascript - 使用 onscroll 检测鼠标滚轮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27325506/

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