移动端事件——移动端滑屏切换的幻灯片(一)

在我们开始用原声JS写移动端轮播前,我们先了解一些移动端的基础。

    touch事件、touchEvents对象、滑屏的思想与实现

移动端touch事件

  • touchstart

  • touchmove

  • touchend

let box = document.querySelector("#box"); /* touchstart --> mousedown 手指触碰元素 touchmove --> mousemove 手指触碰元素之后,在屏幕中移动 touchend --> mouseup 手指触碰元素之后,从屏幕上抬起 */ box.addEventListener("touchstart",()=>{ console.log("手指触碰") }); box.addEventListener("touchmove",({target})=>{ console.log("手指移动",target) }); box.addEventListener("touchend",()=>{ console.log("手指抬起") });
  • touch 事件 和 mouse 事件的区别

{ let box = document.querySelector("#box"); box.addEventListener("mouseup",()=>{ console.log("鼠标抬起");// 移动端也支持 mouse 事件 console.timeEnd(1); }); box.addEventListener("touchend",()=>{ console.log("手指抬起");// PC 端不支持 touch 事件 console.time(1); }); } 
  • 事件点透
    • touch 事件本身没有延迟,触发之后立马执行,另外浏览器会记录当前的一个点击位置,延迟一段时间,在该坐标找到相应的元素,如果元素有 mouse 事件,就执行
      解决方案:
      1. 给 touch 事件 加延迟
      2. 绝对不在页面使用 mouse 事件
      3. 阻止默认事件

    • mouse 事件的延迟问题
let box = document.querySelector("#box");// box.addEventListener("touchend",()=>{// setTimeout(()=>{// box.style.display = "none";// },300);// });box.addEventListener("touchend",(e)=>{ box.style.display = "none"; // setTimeout(()=>{ // box.style.display = "none"; // },300); e.preventDefault();});
  •  阻止默认事件
    •   阻止 touchstart 事件带来的影响

    •   阻止 touchmove 事件带来的影响

document.addEventListener("touchmove",(e)=>{ e.preventDefault(); },{ passive:false // true 不允许阻止默认事件 ,false 允许阻止默认事件 }); // txt.addEventListener("touchstart",()=>{ // txt.focus(); // })

阻止 touchstart 默认事件带来的危害:
1. 所有的 mouse 事件,全部都会失效(包括a标签的href)
2. 滚动条不能拖动
3. 没有办法获得焦点和失去焦点
4. 多指不能缩放页面
5. 长按选中会被阻止,系统菜单也会被阻止

阻止 touchmove 默认事件带来的危害:
1. 滚动条不能拖动
2. 多指不能缩放页面

 

TouchEvent 对象详解

  • touches 当前屏幕上的手指列表

  • targetTouches 当前元素上的手指列表

  • changedTouches 触发当前事件的手指列表

 

滑屏

  • 构思
    1.   摁下时,记录手指坐标和元素坐标

    2.   移动后,获取手指新坐标

    3.   计算手指移动距离 = 用移动后的手指 - 摁下时手指坐标

    4.   移动后的元素位置 = 手指移动距离 + 摁下时元素的坐标

  • 实现
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no"> <title>Document</title> <style> body { margin: 0; } #box { position: fixed; left: 0; top: 20%; width: 100vw; height: 50%; overflow: -hidden; border: 1px solid red; } </style></head><body><div id="box"></div><script>// 滑屏实现{ let box = document.querySelector("#box"); let translateY = 0; // 元素的位置  let startY = 0; // 记录摁下时元素的位置 let startOffset = 0; // 记录摁下时手指坐标 let list = document.querySelector("#list"); box.addEventListener("touchstart",({changedTouches})=>{ startY = translateY; startOffset = changedTouches[0].pageY; }); box.addEventListener("touchmove",({changedTouches})=>{ let nowOffset = changedTouches[0].pageY;//当前手指坐标 let disOffset = nowOffset - startOffset;//手指移动距离 translateY = disOffset + startY; list.style.transform = `translateY(${translateY}px)` });}</script></body></html>

 

因为俺也是在学,如果有遇到什么bug,欢迎和俺一块探讨。

相关文章