JavaScript监听触摸事件代码实例


Posted in Javascript onDecember 30, 2019

这篇文章主要介绍了JavaScript监听触摸事件代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

监听

<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>Wsscat滑动事件Demo</title>
  </head>

  <body>
    <article>上下左右滑动</article>
  </body>
  <style>
    * {
      margin: 0;
      padding: 0;
    }
    
    article {
      background-color: #000000;
      width: 100%;
      height: 100px;
      text-align: center;
      line-height: 100px;
      color: #FFFFFF;
    }
  </style>
  <script>
    (function() {
      var touch = {};
      function direction(startX, changeX, startY, changeY) {
        return Math.abs(startX - changeX) >=
          Math.abs(startY - changeY) ? (startX - changeX > 0 ? 'Left' : 'Right') : (startY - changeY > 0 ? 'Up' : 'Down')
      }
      document.getElementsByTagName('body')[0].addEventListener('touchstart', function(e) {
        touch.startY = e.targetTouches[0].pageY;
        touch.startX = e.targetTouches[0].pageX;
        //console.log("点击时的X坐标" + nStartX + "和Y坐标" + nStartY);
      });
      document.getElementsByTagName('body')[0].addEventListener('touchmove', function(e) {
        touch.whenChangY = e.changedTouches[0].pageY;
        touch.whenChangX = e.changedTouches[0].pageX;
        //console.log("滑动时的X坐标" + nWhenChangX + "和Y坐标" + nWhenChangY);
      })
      document.getElementsByTagName('body')[0].addEventListener('touchend', function(e) {
        touch.changY = e.changedTouches[0].pageY;
        touch.changX = e.changedTouches[0].pageX;
        //console.log("滑动后的X坐标" + nChangX + "和Y坐标" + nChangY);
        var swDirection = direction(touch.startX, touch.changX, touch.startY, touch.changY);
        console.log(swDirection);
      })
    })()
  </script>

</html>

触摸

<!--touchstart
在触摸开始时触发事件
touchend
在触摸结束时触发事件
touchmove
在触摸期间时触发事件-->

<!DOCTYPE html>
<html lang="zh-cn" class="no-js">

  <head>
    <meta http-equiv="Content-Type">
    <meta content="text/html; charset=utf-8">
    <meta charset="utf-8">
    <title></title>
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no">
    <meta name="format-detection" content="telephone=no">
    <meta name="format-detection" content="email=no">
    <link rel="stylesheet" type="text/css" href="css/reset.css" rel="external nofollow" />
  </head>

  <body>
    <div class="page page-1-1 page-current">
      <div class="wrap">
      </div>
    </div>
    <div class="page page-2-1 hide">
      <div class="wrap">
      </div>
    </div>
    <div class="page page-2-2 hide">
      <div class="wrap">
      </div>
    </div>
    <div class="page page-3-1 hide">
      <div class="wrap">
      </div>
    </div>
  </body>
  <script>
    (function() {
      var now = {
          row: 1,
          col: 1
        },
        last = {
          row: 0,
          col: 0
        };
      const towards = {
        up: 1,
        right: 2,
        down: 3,
        left: 4
      };
      var isAnimating = false;
      var touch = {};
      function direction(startX, changeX, startY, changeY) {
        return Math.abs(startX - changeX) >=
          Math.abs(startY - changeY) ? (startX - changeX > 0 ? 'Left' : 'Right') : (startY - changeY > 0 ? 'Up' : 'Down')
      }
      document.getElementsByTagName('body')[0].addEventListener('touchstart', function(e) {
        touch.startY = e.targetTouches[0].pageY;
        touch.startX = e.targetTouches[0].pageX;
        //console.log("点击时的X坐标" + nStartX + "和Y坐标" + nStartY);
      });
      document.getElementsByTagName('body')[0].addEventListener('touchmove', function(e) {
        touch.whenChangY = e.changedTouches[0].pageY;
        touch.whenChangX = e.changedTouches[0].pageX;
        //console.log("滑动时的X坐标" + nWhenChangX + "和Y坐标" + nWhenChangY);
      })
      document.getElementsByTagName('body')[0].addEventListener('touchend', function(e) {
        touch.changY = e.changedTouches[0].pageY;
        touch.changX = e.changedTouches[0].pageX;
        //console.log("滑动后的X坐标" + nChangX + "和Y坐标" + nChangY);
        var swDirection = direction(touch.startX, touch.changX, touch.startY, touch.changY);
        console.log(swDirection);
        //以回调的方法来写这个动作
        if(swDirection == 'Up') {
          swipeUp(function() {
            if(isAnimating) return;
            last.row = now.row;
            last.col = now.col;
            if(now.col == 2) {
              return;
            } else if(last.row != 6) {
              now.row = last.row + 1;
              now.col = 1;
              pageMove(towards.up);
            }
          })
        }
        if(swDirection == 'Down') {
          if(isAnimating) return;
          last.row = now.row;
          last.col = now.col;
          if(now.col == 2) {
            return;
          } else if(last.row != 1) {
            now.row = last.row - 1;
            now.col = 1;
            pageMove(towards.down);
          }
        }
        if(swDirection == 'Left') {
          if(isAnimating) return;
          last.row = now.row;
          last.col = now.col;
          if(last.row > 1 && last.row < 5 && last.col == 1) {
            now.row = last.row;
            now.col = 2;
            pageMove(towards.left);
          }
        }
        if(swDirection == 'Right') {
          if(isAnimating) return;
          last.row = now.row;
          last.col = now.col;
          if(last.row > 1 && last.row < 5 && last.col == 2) {
            now.row = last.row;
            now.col = 1;
            pageMove(towards.right);
          }
        }
      })
      function swipeUp(callback) {
        callback()
      }
      function hasClass(obj, cls) {
        return obj.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
      }
      console.log(window.document)
      function addClass(obj, cls) {
        if(!hasClass(obj, cls)) obj.className += " " + cls;
      }
      function removeClass(obj, cls) {
        if(hasClass(obj, cls)) {
          var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
          obj.className = obj.className.replace(reg, ' ');
        }
      }
      function toggleClass(obj, cls) {
        if(hasClass(obj, cls)) {
          removeClass(obj, cls);
        } else {
          addClass(obj, cls);
        }
      }
      function pageMove(tw) {
        console.log(now);
        console.log(now);
        var lastPage = ".page-" + last.row + "-" + last.col,
          nowPage = ".page-" + now.row + "-" + now.col;
        switch(tw) {
          case towards.up:
            outClass = 'pt-page-moveToTop';
            inClass = 'pt-page-moveFromBottom';
            break;
          case towards.right:
            outClass = 'pt-page-moveToRight';
            inClass = 'pt-page-moveFromLeft';
            break;
          case towards.down:
            outClass = 'pt-page-moveToBottom';
            inClass = 'pt-page-moveFromTop';
            break;
          case towards.left:
            outClass = 'pt-page-moveToLeft';
            inClass = 'pt-page-moveFromRight';
            break;
        }
        isAnimating = true;
        var $nowPage = document.querySelector(nowPage);
        var $lastPage = document.querySelector(lastPage);
        console.log($nowPage);
        removeClass($nowPage, "hide");
        addClass($lastPage, outClass)
        addClass($nowPage, inClass);
        setTimeout(function() {
          removeClass($lastPage, 'page-current');
          removeClass($lastPage, outClass);
          addClass($lastPage, "hide");
          addClass($nowPage, 'page-current');
          removeClass($nowPage, inClass);
          isAnimating = false;
        }, 600);
      }
    })()
  </script>
  <style>
    body {
      width: 100%;
      overflow: hidden;
    }
    
    .page {
      width: 100%;
      height: 100%;
      position: absolute;
      font-size: 100px;
      text-align: center;
    }
    
    .page .wrap {
      height: 500px;
    }
    
    .page-1-1 {
      background-image: url(img/background/1.png);
      background-size: cover;
    }
    
    .page-2-1 {
      background-image: url(img/background/1.png);
      background-size: cover;
    }
    
    .page-2-2 {
      background-image: url(img/background/1.png);
      background-size: cover;
    }
    
    .page-3-1 {
      background-image: url(img/background/1.png);
      background-size: cover;
    }
    
    .page-3-2 {
      background-image: url(img/background/1.png);
      background-size: cover;
    }
    
    .page-4-1 {
      background-image: url(img/background/1.png);
      background-size: cover;
    }
    
    .page-4-2 {
      background-image: url(img/background/1.png);
      background-size: cover;
    }
    
    .page-5-1 {
      background-image: url(img/background/1.png);
      background-size: cover;
    }
    
    .page-current {
      z-index: 1;
    }
    
    .hide {
      display: none;
    }
    
    .pt-page-moveToTop {
      -webkit-animation: moveToTop .6s ease both;
      animation: moveToTop .6s ease both;
    }
    
    @-webkit-keyframes moveToTop {
      from {}
      to {
        -webkit-transform: translateY(-100%);
      }
    }
    
    .pt-page-moveFromBottom {
      -webkit-animation: moveFromBottom .6s ease both;
      animation: moveFromBottom .6s ease both;
    }
    
    @-webkit-keyframes moveFromBottom {
      from {
        -webkit-transform: translateY(100%);
      }
    }
    
    .pt-page-moveToBottom {
      -webkit-animation: moveToBottom .6s ease both;
      animation: moveToBottom .6s ease both;
    }
    
    @-webkit-keyframes moveToBottom {
      from {}
      to {
        -webkit-transform: translateY(100%);
      }
    }
    
    .pt-page-moveFromTop {
      -webkit-animation: moveFromTop .6s ease both;
      animation: moveFromTop .6s ease both;
    }
    
    @-webkit-keyframes moveFromTop {
      from {
        -webkit-transform: translateY(-100%);
      }
    }
    
    .pt-page-moveToRight {
      -webkit-animation: moveToRight .6s ease both;
      animation: moveToRight .6s ease both;
    }
    
    @-webkit-keyframes moveToRight {
      from {}
      to {
        -webkit-transform: translateX(100%);
      }
    }
    
    .pt-page-moveToLeft {
      -webkit-animation: moveToLeft .6s ease both;
      animation: moveToLeft .6s ease both;
    }
    
    @-webkit-keyframes moveToLeft {
      from {}
      to {
        -webkit-transform: translateX(-100%);
      }
    }
  </style>

</html>

触摸前后

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title></title>
  </head>
  <body>
    <!--利用touchstart和touchend触摸前后监听到的四个坐标分别是触摸前的x,y坐标和触摸后的x,y坐标,
    然后用数学公式进行运算得出方向-->
  </body>
  <script type="text/javascript">
    document.getElementsByTagName('body')[0].addEventListener('touchstart', function(e) {
        touch.startY = e.targetTouches[0].pageY;
        touch.startX = e.targetTouches[0].pageX;
        //console.log("点击时的X坐标" + nStartX + "和Y坐标" + nStartY);
      });
    document.getElementsByTagName('body')[0].addEventListener('touchmove', function(e) {
        touch.whenChangY = e.changedTouches[0].pageY;
        touch.whenChangX = e.changedTouches[0].pageX;
        //console.log("滑动时的X坐标" + nWhenChangX + "和Y坐标" + nWhenChangY);
      })
    document.getElementsByTagName('body')[0].addEventListener('touchend', function(e) {
        touch.changY = e.changedTouches[0].pageY;
        touch.changX = e.changedTouches[0].pageX;
        //console.log("滑动后的X坐标" + nChangX + "和Y坐标" + nChangY);
        var swDirection = direction(touch.startX, touch.changX, touch.startY, touch.changY);
  </script>
</html>

GitHub地址:https://github.com/lianglixiong

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
TextArea 控件的最大长度问题(js json)
Dec 16 Javascript
从URL中提取参数与将对象转换为URL查询参数的实现代码
Jan 12 Javascript
jQuery提示效果代码分享
Nov 20 Javascript
JavaScript中对JSON对象的基本操作示例
May 21 Javascript
jQuery插件HighCharts实现的2D回归直线散点效果示例【附demo源码下载】
Mar 09 Javascript
Angular2+国际化方案(ngx-translate)的示例代码
Aug 23 Javascript
浅谈在vue项目中如何定义全局变量和全局函数
Oct 24 Javascript
微信小程序实现列表下拉刷新上拉加载
Jul 29 Javascript
Layui给数据表格动态添加一行并跳转到添加行所在页的方法
Aug 20 Javascript
通过js实现压缩图片上传功能
Feb 25 Javascript
js Math数学简单使用操作示例
Mar 13 Javascript
OpenLayers3实现地图鹰眼以及地图比例尺的添加
Sep 25 Javascript
微信公众号服务器验证Token步骤图解
Dec 30 #Javascript
微信小程序封装多张图片上传api代码实例
Dec 30 #Javascript
使用pkg打包ThinkJS项目的方法步骤
Dec 30 #Javascript
微信小程序实现一个简单swiper代码实例
Dec 30 #Javascript
JavaScript switch语句使用方法简介
Dec 30 #Javascript
微信小程序自定义菜单切换栏tabbar组件代码实例
Dec 30 #Javascript
详解Vue的watch中的immediate与watch是什么意思
Dec 30 #Javascript
You might like
在PHP3中实现SESSION的功能(三)
2006/10/09 PHP
PHP连接MySQL的2种方法小结以及防止乱码
2014/03/11 PHP
ThinkPHP连接数据库及主从数据库的设置教程
2014/08/22 PHP
PHP使用pdo连接access数据库并循环显示数据操作示例
2018/06/05 PHP
FireFox中textNode分片的问题
2007/04/10 Javascript
javascript 避免闭包引发的问题
2009/03/17 Javascript
基于jquery &amp; json的省市区联动代码
2012/06/26 Javascript
如何通过javascript操作web控件的自定义属性
2013/11/25 Javascript
浅谈javascript 函数内部属性
2015/01/21 Javascript
JavaScript中的getMilliseconds()方法使用详解
2015/06/10 Javascript
JQuery自动触发事件的方法
2015/06/13 Javascript
jQuery实现按钮只点击一次后就取消点击事件绑定的方法
2015/06/26 Javascript
IE中document.createElement的iframe无法设置属性name的解决方法
2015/09/14 Javascript
js数组常用操作方法小结(增加,删除,合并,分割等)
2016/08/02 Javascript
BOM系列第一篇之定时器setTimeout和setInterval
2016/08/17 Javascript
利用BootStrap弹出二级对话框的简单实现方法
2016/09/21 Javascript
JavaScript字符串对象
2017/01/14 Javascript
AngularJS之自定义服务详解(factory、service、provider)
2017/04/14 Javascript
基于bootstrop常用类总结(推荐)
2017/09/11 Javascript
JavaScript实现抖音罗盘时钟
2019/10/11 Javascript
[14:57]DOTA2 HEROS教学视频教你分分钟做大人-幽鬼
2014/06/13 DOTA
[01:25]2014DOTA2国际邀请赛 zhou分析LGD比赛情况
2014/07/14 DOTA
[01:03:03]VP vs Mineski 2018国际邀请赛淘汰赛BO3 第一场 8.22
2018/08/23 DOTA
Python利用带权重随机数解决抽奖和游戏爆装备问题
2016/06/16 Python
用python实现的线程池实例代码
2018/01/06 Python
pandas.dataframe中根据条件获取元素所在的位置方法(索引)
2018/06/07 Python
Python字典的核心底层原理讲解
2019/01/24 Python
简单介绍一下pyinstaller打包以及安全性的实现
2020/06/02 Python
python环境搭建和pycharm的安装配置及汉化详细教程(零基础小白版)
2020/08/19 Python
canvas画图被放大且模糊的解决方法
2020/08/11 HTML / CSS
美国滑板店:Tactics
2020/11/08 全球购物
物业管理毕业生个人的求职信
2013/11/30 职场文书
村党建工作汇报材料
2014/11/02 职场文书
浅谈redis缓存在项目中的使用
2021/05/20 Redis
浅谈redis整数集为什么不能降级
2021/07/25 Redis
MySQL分库分表详情
2021/09/25 MySQL