分享一段代码实例,它能够实现判断移动端触屏位置的功能。
代码实例如下:
   [ 其他 ] 运行代码    下载代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0"/>
<meta name="format-detection" content="telephone=no" />
<title>51前端</title>
<style type="text/css">
div{
  margin:20px 0;
  font-size: 18px;
}
#container{
  width:100%;
  height:420px;
background-color: #1AC78C;
}
</style>
</head>
<body>
<div>
  <h3>触摸开始</h3>
  <p>触摸方向为:<span id="direction"></span></p>
</div>
<div id="container"></div>
<script type="text/javascript">
var container = document.getElementById("container");
var direction = document.getElementById("direction");
var start_x;
var start_y;
var end_x;
var end_y;
container.addEventListener("touchstart", function(event) {
  if (event.targetTouches.length == 1) {
    var touch = event.targetTouches[0];
    start_x = touch.pageX;
    start_y = touch.pageY;
  };
});
container.addEventListener("touchmove", function(event) {
  event.preventDefault();
  if (event.targetTouches.length == 1) {
    var touch = event.targetTouches[0];
    move_x = touch.pageX;
    move_y = touch.pageY;
  };
});
container.addEventListener("touchend", function(event) {
  if (event.changedTouches.length == 1) {
    var touch = event.changedTouches[0];
    end_x = touch.pageX;
    end_y = touch.pageY;
  };
  var directionMsg = "";
  var numRange = 20;
  if (start_x - end_x > numRange) {
    directionMsg += "左";
  } else if (start_x - end_x < -numRange) {
    directionMsg += "右";
  }
  
  if (start_y - end_y > numRange) {
    directionMsg += "上";
  } else if (start_y - end_y < -numRange) {
    directionMsg += "下";
  }
  direction.innerHTML = directionMsg;
});
</script>
</body>
</html>

代码描述:JavaScript 判断触屏位置,JavaScript判断触屏位置



3 4



用户评论
大牛,别默默的看了,快登录帮我点评一下吧!:)      登录 | 注册


热门标签: js js代码 js实例 javascript javascript代码 javascript实例 js条件语句 javascript条件语句

×
×

注册

官方QQ群

扫描上面二维码加微信群

官方QQ群

jQuery/js讨论群
群号:642649996
Css3+Html5讨论群
群号:322131262

加群请备注:从官网了解到