好吧,它并不漂亮,但这应该可以解决问题:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function handle() { console.log("fired"); };
</script>
</head>
<body>
<div id="div" style="width:200px; height:100px; overflow-y: scroll; border: 1px solid gray;">
<div style="width:150px; height:400px;"> </div>
</div>
<script>
//Get the element
var div = document.getElementById("div");
var ignore = true;
//Set the scroll to 1 (this will allow it to scroll up)
div.scrollTop = 1;
div.addEventListener("scroll", function(){
//Ignore generating output if the code set the scroll position
if(ignore) {
ignore = !ignore;
return;
}
//CODE GOES HERE
handle();
//If the scroll is at the top, go down one so that the user
//is still allowed to scroll.
if(div.scrollTop <= 1) {
ignore = true;
div.scrollTop = 1;
}
//If the scroll is at the bottom, go up one so the user can
//still scroll down
else if(div.scrollTop >= div.scrollHeight-div.clientHeight - 1) {
ignore = true;
div.scrollTop = div.scrollHeight-div.clientHeight - 1;
}
}, true);
</script>
</body>
</html>
我删除了内联函数调用并将其替换为eventListener
. 基本上,它确保用户永远不会完全滚动到顶部或底部,从而确保始终存在滚动事件。