[英]Javascript: horizontal autoscroll
如果用戶拖動容器中靠近水平邊緣的元素,則需要將容器在相應方向上自動滾動到末端。
下面的代碼如何進行改進?
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);
}
}
謝謝你的幫助。
我不知道當前的代碼是否有效,但這是一個更有條理的版本。
const scroller={
speed: 10,
sensitivity: 10,
container: document.getElementById("scrollContainer"),
rect: scroller.container.getBoundingClientRect(),
interval: null,
offsetX: 0,
offsetY: 0
};
scroller.container.addEventListener("touchmove",function(e){
clearInterval(scroller.interval);
scroller.interval = null; // May not be needed
// pointer offset
scroller.offsetX = e.targetTouches[0].pageX;
scroller.offsetY = e.targetTouches[0].pageY;
// the container should scroll
// pointer is over right / left edge of a scroller.container
if((scroller.rect.width+scroller.rect.left-scroller.offsetX<=scroller.sensitivity)&&(scroller.offsetY>scroller.rect.top))scroller.interval=setInterval(()=>{scroller.container.scrollLeft+=scroller.speed;},10);
if((scroller.offsetX-scroller.rect.left<=scroller.sensitivity)&&(scroller.offsetY>scroller.rect.top))scroller.interval=setInterval(()=>{scroller.container.scrollLeft-=scroller.speed;},10);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.