为什么JavaScript中移动端使用ontouchend无法获取touches数组
我想做一个获取滑动距离的效果,但是发现在document.documentElement.ontouchstart=function(e){console.log(e.t...
我想做一个获取滑动距离的效果,但是发现在document.documentElement.ontouchstart = function(e) { console.log(e.touches[0]); StartPos = { x: e.touches[0].clientX, y: e.touches[0].clientY }; }中,可以正确获取到touches[0] document.documentElement.ontouchend= function(e) { console.log(e.touches[0]); EndPos = { x: e.touches[0].clientX, y: e.touches[0].clientY };这样却无法输出请问哪里有错了,或者应该怎么改?
展开
2个回答
展开全部
<!DOCTYPE HTML>
<html>
<head>
<title>Page Title</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script>
function load (){
document.addEventListener('touchstart',touch, false);
document.addEventListener('touchmove',touch, false);
document.addEventListener('touchend',touch, false);
function touch (event){
var event = event || window.event;
var oInp = document.getElementById("inp");
switch(event.type){
case "touchstart":
oInp.innerHTML = "Touch started (" + event.touches[0].clientX + "," + event.touches[0].clientY + ")";
break;
case "touchend":
oInp.innerHTML = "<br>Touch end (" + event.changedTouches[0].clientX + "," + event.changedTouches[0].clientY + ")";
break;
case "touchmove":
event.preventDefault();
oInp.innerHTML = "<br>Touch moved (" + event.touches[0].clientX + "," + event.touches[0].clientY + ")";
break;
}
}
}
window.addEventListener('load',load, false);
</script>
</head>
<body>
<div id="inp"></div>
</body>
</html>
追问
请问你知道我这个代码为什么不能实现吗
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询