【问题标题】:Detect swipe direction without scrolling无需滚动即可检测滑动方向
【发布时间】:2019-01-26 15:20:27
【问题描述】:

如何在不实际滚动的情况下检测滑动方向?这是我正在做的事情:

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';
  }
});
<div style='height: 2000px; border: 5px solid gray; touch-action: none;'>
	<p id='status'></p>
</div>

我观察到的是,虽然屏幕没有滚动,但没有任何事件监听器代码执行。这是因为事件中没有“deltaY”属性。我使用桌面上的equivalent code 和'wheel' 事件来检测滚动方向而不滚动。

【问题讨论】:

    标签: javascript mobile scroll


    【解决方案1】:

    这就是我所做的:

    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';
      }
    });
    

    【讨论】:

      猜你喜欢
      • 2023-03-04
      • 2019-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-18
      • 1970-01-01
      相关资源
      最近更新 更多