qq_科比王_0
2016-01-29 16:07
<body>
<div id="div1">
touch滑动
</div>
<script type="text/javascript" src="js/zepto.js"></script>
<script type="text/javascript">
window.onload = function(){
var oDiv1 = document.querySelector("#div1");
//获取touch的position;
function getTouchPos(e){
var touches = e.touches;
if(touches && touches[0]){
return {
x : touches[0].clientX,
y : touches[0].clientY
}
}
return {x : touches.clinetX, y : touches.clientY}
}
function getDis(p1, p2){
var dis = Math.sqrt(Math.pow(p1.x-p2.x, 2) + Math.pow(p1.y - p2.y, 2));
if(!p1 || !p2){
return 0;
}
return dis;
}
function getAngle(p1,p2){
var angle = Math.atan2(p2.y-p1.y, p2.x-p1.x);
var a = angle*180/Math.PI;
return a;
}
function getDirection(p1,p2){
var angle = getAngle(p1, p2);
var dir = "";
if(angle>-45 && angle<=45){
dir = "left"
}else if(angle > 45 && angle <= 135){
dir = "top"
}else if(angle >135 && angle <= -135){
dir = "right"
}else if(angle >-135 && angle <= -45){
dir = "bottom"
}
return dir;
}
var startTime = 0;
var startPos = {};
var endTime = 0;
var endPos = {};
var startTouchHandle=function(e){
startPos = getTouchPos(e);
startTime = Date.now();
}
var moveTouchHandle=function(e){
endPos = getTouchPos(e);
endTime = Date.now();
}
var endTouchHandle=function(e){
endPos = getTouchPos(e);
var dir = getDirection(startPos,endPos);
//由于事件绑定时没有把“e”这个参数传进去,因此这里弹出的是undefined;
alert(endPos.y);
switch(dir){
case "left":
oDiv1.innerHTML = "left"
break;
case "right":
oDiv1.innerHTML = "right"
break;
case "top":
oDiv1.innerHTML = "top"
break;
case "bottom":
oDiv1.innerHTML = "bottom"
break;
}
}
var touchStart = "";
var touchMove = "";
var touchEnd = "";
if("ontouchstart" in window){
touchStart = "touchstart";
touchMove = "touchmove";
touchEnd = "touchend";
}else{
touchStart = "mousedown";
touchMove = "mousemove";
touchEnd = "mouseup";
}
oDiv1.addEventListener(touchStart, startTouchHandle)
oDiv1.addEventListener(touchMove, moveTouchHandle)
oDiv1.addEventListener(touchEnd, endTouchHandle)
//像下面这样写就正常
/*oDiv1.addEventListener(touchStart, function(e){
endTouchHandle(e)
},false)*/
}
</script>
</body>
首先,题主对形参和实参的概念没有弄清楚。
然后,题主对touch事件的下的三个属性没有弄清楚 touches targetToutches changedTouches分别代表什么?
题主把最后最后的touchStart 换成 touchEnd之后 你会发现 ,你所谓的成长写法还是无效的 , 因为touchEnd触发的Event事件根本不会有touches属性
Hello,移动WEB
110230 学习 · 177 问题
相似问题