【发布时间】:2018-06-24 16:30:06
【问题描述】:
如果用户在靠近水平边缘的容器中拖动元素,我需要将容器自动滚动到相应方向的末尾。
如何改进下面的代码?
const scrollSpeed = 10;
const scrollSensitivity = 10;
let scrollInterval = null;
const scrollContainer = document.getElementById("scrollContainer");
scrollContainer.addEventListener("touchmove", autoScroll);
function disableAutoScrolling() {
clearInterval(scrollInterval);
scrollInterval = null;
}
function autoScroll(event) {
// pointer offset
const offsetX = event.targetTouches[0].pageX;
const offsetY = event.targetTouches[0].pageY;
// container offset relative to viewport
const rect = scrollContainer.getBoundingClientRect();
// pointer is over right / left edge of a scrollContainer
const SCROLL_RIGHT = ( rect.width + rect.left - offsetX <= scrollSensitivity ) && ( offsetY > rect.top );
const SCROLL_LEFT = ( offsetX - rect.left <= scrollSensitivity ) && ( offsetY > rect.top );
disableAutoScrolling();
// the container should scroll
if (SCROLL_RIGHT) {
scrollInterval = setInterval(() => {
scrollContainer.scrollLeft += scrollSpeed;
}, 10);
}
if (SCROLL_LEFT) {
scrollInterval = setInterval(() => {
scrollContainer.scrollLeft -= scrollSpeed;
}, 10);
}
}
感谢您的帮助。
【问题讨论】:
-
您想在这里改进什么?有什么问题吗?请更具体。
标签: javascript scroll autoscroll