html
瀏覽器
spa
touchstartscala
touchmovecode
orm
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("手指擡起") });
htm
{ 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. 阻止默認事件對象
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(); });
blog
事件
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,歡迎和俺一塊探討。