-
touchstart
-
touchmove
-
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("手指抬起") });
{ 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(); });
- 阻止默認事件
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 對象詳解
-
-
targetTouches 當前元素上的手指列表
-
-
-
摁下時,記錄手指坐標和元素坐標
-
移動后,獲取手指新坐標
-
計算手指移動距離 = 用移動后的手指 - 摁下時手指坐標
-
-
<!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,歡迎和俺一塊探討。