touch事件範本

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="target-densitydpi=320,width=640,user-scalable=no">
<title>touch上下滑動</title>
<script type="text/javascript" src="jquery-1.11.3.js"></script>
</head>
<style type="text/css">
body{
margin: 0;padding: 0;
}
.box{
width:100%;
height: 100%;
position: fixed;
margin:auto;
top: 0;
left: 0;
right:0;
bottom: 0;
background: red;
opacity: 0.6;
color: black;
overflow: hidden;
}
.none{
display: none;
}
.dd1{
width: 640px;
height: 640px;
background: #0000FF;
}
</style>
<body>
<div class="box" id="box">dssdfsdfsdffffffffffffffffffffffffffffffffs</div>
<div class="dd1 none" id="dd"></div>
</body>
<script type="text/javascript">
function _touch(){
var startx,starty;//讓startx在touch事件函數裏是全局性變量。
var endx,endy;
var el=document.getElementById('box');
var ee=document.getElementById('dd');
function cons(){ //獨立封裝這個事件能夠保證執行順序,從而可以訪問獲得應該訪問的數據。
console.log(starty,endy);
//alert(starty);
var l=Math.abs(startx-endx);
var h=Math.abs(starty-endy);
if(l>h){
//x事件
if(startx>endx){
alert('left');
}else{
alert('right');
}
}else{
//y事件
if(starty>endy){
alert('top');
}else{
alert('bottom');

$(".dd1").removeClass("none");
$(".box").addClass("none");


}
}
// if(startx>endx){ //判斷左右移動程序
// alert('left');
// }else{
// alert('right');
// }
}
el.addEventListener('touchstart',function(e){
var touch=e.changedTouches;
startx=touch[0].clientX;
starty=touch[0].clientY;
});
el.addEventListener('touchend',function(e){
var touch=e.changedTouches;
endx=touch[0].clientX;
endy=touch[0].clientY;
cons(); //startx endx 的數據收集應該放在touchend事件後執行,而不是放在touchstart事件裏執行,這樣才能訪問到touchstart和touchend這2個事件產生的startx和endx數據。另外startx和endx在_touch事件函數裏是全局性的,因此在此函數中均可以訪問獲得,因此只須要注意事件執行的前後順序便可。
});


ee.addEventListener('touchstart',function(e){
var touch=e.changedTouches;
startx=touch[0].clientX;
starty=touch[0].clientY;
});
ee.addEventListener('touchend',function(e){
var touch=e.changedTouches;
endx=touch[0].clientX;
endy=touch[0].clientY;
cons(); //startx endx 的數據收集應該放在touchend事件後執行,而不是放在touchstart事件裏執行,這樣才能訪問到touchstart和touchend這2個事件產生的startx和endx數據。另外startx和endx在_touch事件函數裏是全局性的,因此在此函數中均可以訪問獲得,因此只須要注意事件執行的前後順序便可。
});
}
_touch();
</script>
</html>javascript

相關文章
相關標籤/搜索