touch.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // 移动端事件
  2. var touch = {
  3. // 点击
  4. tap(classname, callback) {
  5. let classList = document.querySelectorAll(classname)
  6. for(let i = 0; i < classList.length; i++) {
  7. classList[i].addEventListener( 'touchstart' ,callback)
  8. }
  9. },
  10. // 滑动
  11. direction: function (target, upCallback) {
  12. target.addEventListener("touchstart", handleTouchEvent)
  13. target.addEventListener("touchend", handleTouchEvent)
  14. target.addEventListener("touchmove", handleTouchEvent)
  15. var startX;
  16. var startY;
  17. function handleTouchEvent(event) {
  18. switch (event.type){
  19. case "touchstart":
  20. startX = event.touches[0].pageX;
  21. startY = event.touches[0].pageY;
  22. break;
  23. case "touchend":
  24. var spanX = event.changedTouches[0].pageX - startX;
  25. var spanY = event.changedTouches[0].pageY - startY;
  26. console.log(spanY)
  27. if(Math.abs(spanX) > Math.abs(spanY)){ //认定为水平方向滑动
  28. if(spanX > 30){ //向右
  29. } else if(spanX < -30){ //向左
  30. }
  31. } else { //认定为垂直方向滑动
  32. if(spanY > 30){ //向下
  33. upCallback()
  34. } else if (spanY < -30) {//向上
  35. }
  36. }
  37. break;
  38. case "touchmove":
  39. //阻止默认行为
  40. event.preventDefault();
  41. break;
  42. }
  43. }
  44. }
  45. }
  46. export default touch