use*_*706 2 javascript mobile scroll
如何在不实际滚动的情况下检测滑动方向?这就是我正在做的:
function preventDefault(e) {
e = e || window.event;
if (e.preventDefault)
e.preventDefault();
e.returnValue = false;
}
window.ontouchmove = preventDefault;
window.addEventListener('touchmove', function(e) {
if (e.deltaY < 0) {
console.log('scrolling up');
document.getElementById('status').innerHTML = 'scrolling up';
}
if (e.deltaY > 0) {
console.log('scrolling down');
document.getElementById('status').innerHTML = 'scrolling down';
}
});Run Code Online (Sandbox Code Playgroud)
<div style='height: 2000px; border: 5px solid gray; touch-action: none;'>
<p id='status'></p>
</div>Run Code Online (Sandbox Code Playgroud)
我观察到,虽然屏幕不滚动,但没有任何事件侦听器代码执行。这是因为事件中没有“deltaY”属性。我在桌面上使用了等效的代码和“wheel”事件来检测滚动方向而不滚动。
这就是我所做的:
let start = null;
window.addEventListener('touchstart', function(e) {
start = e.changedTouches[0];
});
window.addEventListener('touchend', function(e) {
let end = e.changedTouches[0];
if(end.screenY - start.screenY > 0)
{
console.log('scrolling up');
document.getElementById('status').innerHTML = 'scrolling up';
}
else if(end.screenY - start.screenY < 0)
{
console.log('scrolling down');
document.getElementById('status').innerHTML = 'scrolling down';
}
});
Run Code Online (Sandbox Code Playgroud)