移动端事件(一)—— 移动端事件和对象
-
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,欢迎和俺一块探讨。

浙公网安备 33010602011771号