一、移动端的事件

一、移动端的事件

移动端新增了“touch”触摸事件,因为手指的行为叫“触摸”,而鼠标的行为叫“点击”

依然支持点击事件,只是有300ms的延迟

举例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var box = document.getElementById("box");
// 获取当前时间
var date = new Date();
// 绑定click事件
box.onclick = function(){
// 改变文字颜色
this.style.color = "white";
console.log("onclick", new Date() - date);
}

// touchstart事件
// 使用dom2级绑定方式
box.addEventListener("touchstart", function(){
// 改变文字颜色
this.style.color = "blue";
console.log("touchstart", new Date() - date);
});

这两个数值就是两个事件执行的毫秒值差:

U8p6dH.png

1.1 移动端的三个事件

1
2
3
触摸开始事件:touchstart
触摸移动事件:touchmove
触摸结束事件:touchend

绑定方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// touchstart
box.addEventListener("touchstart", function(){
console.log("触摸开始");
});

// touchmove
box.addEventListener("touchmove", function(){
console.log("触摸中");
});

// touchend
box.addEventListener("touchend", function(){
console.log("触摸结束");
});

U8phSP.png

1.2 事件对象

touchstarttouchmove可以通过e.touches来获取手指的相关信息:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// touchstart
box.addEventListener("touchstart", function(e){
console.log(e);
// 查看手指相关信息
console.log(e.touches[0]);
// 查看手指位置
console.log("X:", e.touches[0].clientX);
// 查看手指位置
console.log("Y", e.touches[0].clientY);
});

// touchmove
box.addEventListener("touchmove", function(e){
console.log(e);
// 查看手指相关信息
console.log(e.touches[0]);
// 查看手指位置
console.log("X:", e.touches[0].clientX);
// 查看手指位置
console.log("Y", e.touches[0].clientY);
});

U8pzOU.png

touchend通过e.changedTouches来获取手指的相关信息

1
2
3
4
5
6
7
8
9
10
11
12
// touchend
box.addEventListener("touchend", function(e){
console.log(e);
// 查看手指相关信息
console.log(e.changedTouches[0]);
// 查看手指位置
console.log("X:", e.changedTouches[0].clientX);
// 查看手指位置
console.log("Y", e.changedTouches[0].clientY);
});

// touchend事件中,获取手指信息的属性不是通过 e.touches 来获取,而是通过 e.changedTouches来获取

U899w4.png

点击查看

本文标题:一、移动端的事件

文章作者:Mango

发布时间:2020年07月14日 - 13:09:56

最后更新:2020年07月14日 - 13:27:10

原始链接:https://mango185.github.io/post/94abbcc9.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

-------------------本文结束 感谢您的阅读-------------------