我正在尝试制作一张垂直幻灯片,它可以在带有wheel事件的桌面上运行,但是scrollIntoView方法不会在触摸事件侦听器中执行。
这是代码
let startClientY, endClientY;
page.addEventListener("touchstart", (event) => {
startClientY = event.touches[0].pageY;
}, false);
page.addEventListener("touchmove", (event) => {
endClientY = event.touches[0].pageY;
}, false);
page.addEventListener("touchend", (event) => {
let diff = startClientY - endClientY;
if (diff < -35) {
if( i !== 0 ) {
slides[i - 1].scrollIntoView({
behavior: "smooth", block: "start"
});
i--;
console.log('scroll top'); // this code is executed as well
}
} else if (diff > 35) {
if( i < slides.length -1) {
slides[i + 1].scrollIntoView({
behavior: "smooth", block: "start"
});
i++;
console.log('scroll down'); // this code is executed
}
}
startClientY = undefined;
endClientY = undefined;
}, false);
奇怪的是,控制台条件内的日志已执行,并且scrollIntoView方法在eventListeners之外起作用
我想念什么?
答案 0 :(得分:0)
问题来自触摸事件监听器中的scrollIntoView行为选项,我发现了另一种实现我想要的方法的方法。
let slideHeight = page.offsetHeight;
page.addEventListener("touchstart", function (event) {
startClientY = event.touches[0].pageY;
}, {
capture: true,
passive: true
});
page.addEventListener("touchmove", function (event) {
endClientY = event.touches[0].pageY;
}, {
capture: true,
passive: true
});
page.addEventListener("touchend", (event) => {
let diff = startClientY - endClientY;
if (diff < -35) {
if (i !== 0) {
page.scrollBy(0, -slideHeight);
i--;
}
} else if (diff > 35) {
if (i < slides.length - 1) {
page.scrollBy(0, slideHeight);
i++;
}
}
startClientY = undefined;
endClientY = undefined;
}, {
capture: true,
passive: true
});
其中页面变量是我的幻灯片 希望对您有所帮助!