代码来源:http://www.lanrenzhijia.com/js/css3/3206.html

<html lang="en"><head>
<meta charset="UTF-8">
<meta content="width=device-width, initial-scale=1,maximum-scale=1,maximum-scale=1, user-scalable=no" name="viewport">
<title>懒人原生touch事件,计算滑动距离</title>
<style>
*{margin:0;padding:0;}
#demo{width:100%;height:500px;float:left;}
</style>
</head>
<body>
<div id="demo">
请用移动设备访问,滑动屏幕后即可弹出滑动距离
</div>
<script>
var b = document.getElementsByTagName("body")[0];
b.addEventListener("touchmove", function(e){
e.preventDefault();
});
(function(){
var startX,startY,endX,endY,moveLength;
var el = document.querySelector("#demo");
//获取点击开始的坐标
el.addEventListener("touchstart", function (e){
startX = e.touches[0].pageX;
startY = e.touches[0].pageY;
});
//获取点击结束后的坐标
el.addEventListener("touchend", function(e){
endX = e.changedTouches[0].pageX;
endY = e.changedTouches[0].pageY;
var x = Math.abs(endX - startX);
var y = Math.abs(endY - startY);
//长方形的斜边长 = 两个直线的平方的和的平方根
moveLength = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
alert("本次的移动距离为:"+moveLength);
})
})();
</script>

</body></html>

posted on 2018-01-26 15:20  刘世涛6192  阅读(947)  评论(0编辑  收藏  举报