标签:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" Content="text/html; charset=utf-8;">
<title>移动端触摸滑动</title>
<meta name="viewport" content="target-densitydpi=320,width=640,user-scalable=no">
<style>
*{margin:0;padding:0;}
html{height: 100%;}
body{ height: 100%;}
</style>
</head>
<body id=‘box‘>
<script>
var myBox = document.getElementById(‘box‘);
var slider = {
//判断设备是否支持touch事件
touch:(‘ontouchstart‘ in window) || window.DocumentTouch && document instanceof DocumentTouch,
slider:document.getElementById(‘box‘),
//事件
events:{
index:0, //显示元素的索引
slider:myBox, //this为slider对象
handleEvent:function(event){
var self = this; //this指events对象
if(event.type == ‘touchstart‘){
self.start(event);
}else if(event.type == ‘touchmove‘){
self.move(event);
}else if(event.type == ‘touchend‘){
self.end(event);
}
},
//滑动开始
start:function(event){
var touch = event.targetTouches[0]; //touches数组对象获得屏幕上所有的touch,取第一个touch
startPos = {x:touch.pageX,y:touch.pageY,time:+new Date}; //取第一个touch的坐标值
console.log(‘startPos data as:‘ + ‘startPos.x =‘ + startPos.x+ ‘startPos.y =‘ + startPos.y);
isScrolling = 0; //这个参数判断是垂直滚动还是水平滚动
myBox.addEventListener(‘touchmove‘,this,false);
myBox.addEventListener(‘touchend‘,this,false);
},
//移动
move:function(event){
//当屏幕有多个touch或者页面被缩放过,就不执行move操作
if(event.targetTouches.length > 1 || event.scale && event.scale !== 1) return;
var touch = event.targetTouches[0];
endPos = {x:touch.pageX - startPos.x,y:touch.pageY - startPos.y};
console.log(‘endPos data as:‘ + ‘touch.x =‘ + touch.pageX+ ‘touch.y =‘ + touch.pageY);
isScrolling = Math.abs(endPos.x) < Math.abs(endPos.y) ? 1:0; //isScrolling为1时,表示纵向滑动,0为横向滑动
event.preventDefault();
},
//滑动释放
end:function(event){
var duration = +new Date - startPos.time; //滑动的持续时间
if(isScrolling === 0){ //当为水平滚动时
if(Number(duration) > 10){
//判断是左移还是右移,当偏移量大于10时执行
if(endPos.x > 10){ //向右移动
console.log(‘向右移动‘);
}else if(endPos.x < -10){ //向左移动
console.log(‘向左移动‘);
}
}
}else{
if(Number(duration) > 10){
//判断是上移还是下移,当偏移量大于10时执行
if(endPos.y > 10){ //向下移动
console.log(‘向下移动‘);
}else if(endPos.y < -10){ //向上移动
console.log(‘向上移动‘);
}
//myBox.style.left = touch.pageX + ‘px‘;
}
}
//解绑事件
myBox.removeEventListener(‘touchmove‘,this,false);
myBox.removeEventListener(‘touchend‘,this,false);
}
},
//初始化
init:function(){
var self = this; //this指slider对象
if(!!self.touch) self.slider.addEventListener(‘touchstart‘,self.events,false); //addEventListener第二个参数可以传一个对象,会调用该对象的handleEvent属性
}
};
slider.init();
</script>
</body>
</html>
标签:
原文地址:http://www.cnblogs.com/tuoq/p/4682956.html