这是一个事件绑定的问题,我这个写法和上课时老师讲的写法是一样的,为什么我这个就会出错呢?主要原因是事件绑定时没有将“e”传进去,但是老师上课时也没有传进去呀,怎么他的就可以呢?
<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>