移动端事件有两类:
触屏(常用)
指针(了解,兼容性问题很大)
//触屏 指针
/*
touchstart(手指按下) 类似于pc端的mousedown
touchmove(手指移动) 类似于pc端的mousemove
不可能单独触发 可以单独触发
touchend(手指抬起) 类似于pc端的mouseup
*/
触屏事件不要使用dom0绑定(低版本的没效果)
var item = document.querySelector(".item");
item.addEventListener("touchstart",function(){
console.log("touchstart")
})
item.addEventListener("touchmove",function(){
console.log("touchmove")
})
item.addEventListener("touchend",function(){
console.log("touchend")
})
触屏事件的默认行为:
1.手指长按可以复制
2.下滑有橡皮筋效果
但是,为了触屏事件干净需要禁止事件的默认行为
document.addEventListener("touchstart",function(ev){
ev=ev||event;
ev.preventDefault();//阻止系统触屏事件的默认行为
})
这样可以使某个元素具有默认行为
/*var item = document.querySelector(".item");
item.addEventListener("touchstart",function(ev){
ev=ev||event;
ev.stopPropagation();
})*/
/*var item = document.querySelector(".item");
item.addEventListener("touchstart",function(ev){
ev=ev||event;
console.log(ev.cancelable);
ev.preventDefault();
})*/
隐患: 全面禁止了触屏事件的默认行为就不会有系统默认滚动条,所以需要自己手写滚动条
事件点透
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=no" />
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
.item{
position: absolute;
left: 0;
top: 0;
width: 200px;
height:200px;
background: pink;
opacity: .5;
}
</style>
</head>
<body>
<div class="item"></div>
<a href="https://www.baidu.com/">去百度</a>
</body>
<script type="text/javascript">
window.onload=function(){
/*
1.pc端的事件可以在移动端触发
2.PC端事件有300毫秒延迟
3.移动端事件不会有延迟
如果要达到这种目的就使用pc端的click事件
*/
var item = document.querySelector(".item");
var a = document.querySelector("a");
item.addEventListener("click",function(){
console.log("click");
})
//touchstart事件立马执行, 等300ms看是否是双击,如果是单击的就会触发下面的a标签跳转
item.addEventListener("touchstart",function(){
this.style.display="none";
})
a.addEventListener("click",function(){
console.log("click");
})
}
</script>
</html>
移动端滑动防误触方案
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=no" />
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<a href="https://www.baidu.com/">去百度</a>
<a href="https://www.baidu.com/">去百度</a>
<a href="https://www.baidu.com/">去百度</a>
<a href="https://www.baidu.com/">去百度</a>
<a href="https://www.baidu.com/">去百度</a>
<a href="https://www.baidu.com/">去百度</a>
</body>
<script type="text/javascript">
window.onload=function(){
document.addEventListener("touchstart",function(ev){
ev=ev||event;
ev.preventDefault();
})
//移动端a标签的跳转方案 解决误触
var aNodes = document.querySelectorAll("a");
for(var i=0;i<aNodes.length;i++){
aNodes[i].addEventListener("touchstart",function(){
this.isMoved=false;
})
aNodes[i].addEventListener("touchmove",function(){
this.isMoved=true;
})
aNodes[i].addEventListener("touchend",function(){
if(!this.isMoved){
location.href=this.href;
}
})
}
}
</script>
</html>
触屏事件对象的3个重要属性
changedTouches:触发当前事件的手指列表
targetTouches:触发当前事件时元素上剩余的手指列表
touches:触发当前事件时屏幕上剩余的手指列表