在手机浏览器中,触屏拖动方块
<!DOCTYPE html>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
<head>
<title>touch test </title>
</head>
<body>
<div id="spirit" style="position:absolute; width:100px; height:100px; left:100px; top:150px; background:#000099;"></div>
</body>
<script type="text/javascript">
var spirit = document.getElementById("spirit");
spirit.addEventListener("touchmove", touchMove, false);
function touchMove(e) {
e.preventDefault();
var touch = e.touches[0];
spirit.style.left = touch.pageX + 'px';
spirit.style.top = touch.pageY + 'px';
}
</script>
</html>
需要处理开始按下和结束
<!DOCTYPE html>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
<head>
<title>touch test </title>
</head>
<body>
<div id="spirit" style="position:absolute; width:100px; height:100px; left:100px; top:150px; background:#000099;"></div>
</body>
<script type="text/javascript">
var spirit = document.getElementById("spirit");
spirit.addEventListener("touchmove", touchMove, false);
function touchStart(e) {
e.preventDefault();
//当手按下时处理代码
}
function touchMove(e) {
e.preventDefault();
//手指按下并滑动时处理的代码
var touch = e.touches[0];
spirit.style.left = touch.pageX + 'px';
spirit.style.top = touch.pageY + 'px';
}
function touchEnd(e) {
//拿起手时处理代码
}
canvas.addEventListener("touchstart", touchStart, false);
canvas.addEventListener("touchmove", touchMove, false);
canvas.addEventListener("touchend", touchEnd, false);
</script>
</html>