我有一个可滚动的 html 元素,它比屏幕宽。并且有迷你滚动地图来显示滚动位置。
在触摸设备上,当用户进行滑动移动然后结束触摸时,元素会继续滚动一段时间。如何使用 javascript 检测此滚动以更新迷你滚动地图?
您可以监听滚动事件并通过超时计时器检测滚动结束。
const scrollElement = document.getElementById("element");
const scrollEndTime = 50 // time until callback fires when no scroll reaches
let scrollEndTimeout = null;
// Callback that fires when your scroll end has reached
function scrollEndCallback() {
// Do whatever you want in here
}
scrollElement .addEventListener('scroll', () => {
if (scrollEnd !== null) {
// clears the previous timeout that has been set in the scorll
clearTimeout(scrollEndTimeout);
}
// in every scroll set a new timeout that gets cleared when the next scroll event appears or fires when no other reaches
scrollEndTimeout = setTimeout(() => {
scrollEndCallback();
}, scrollEndTime);
});