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 相关文章推荐
ajax上传时参数提交不更新等相关问题
Dec 11 Javascript
jquery通过a标签删除table中的一行的代码
Dec 02 Javascript
js整数字符串转换为金额类型数据(示例代码)
Dec 26 Javascript
JavaScript中匿名、命名函数的性能测试
Sep 04 Javascript
iScroll中事件点击触发两次解决方案
Mar 11 Javascript
jQuery鼠标悬浮链接弹出跟随图片实例代码
Jan 08 Javascript
jQuery实现最简单的切换图效果【可兼容IE6、火狐、谷歌、opera等】
Sep 04 Javascript
JavaScript实现的浏览器下载文件的方法
Aug 09 Javascript
Vuex持久化插件(vuex-persistedstate)解决刷新数据消失的问题
Apr 16 Javascript
Vue通过for循环随机生成不同的颜色或随机数的实例
Nov 09 Javascript
微信小程序实现拨打电话功能的示例代码
Jun 28 Javascript
vue+iview实现手机号分段输入框
Mar 25 Vue.js
微信公众号服务器验证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
PHP 变量的定义方法
2010/01/26 PHP
jQuery 源码分析笔记
2011/05/25 PHP
php中explode与split的区别介绍
2012/10/03 PHP
php cli换行示例
2014/04/22 PHP
php获取文章上一页与下一页的方法
2014/12/01 PHP
聊聊 PHP 8 新特性 Attributes
2020/08/19 PHP
HR vs ForZe BO3 第一场 2.13
2021/03/10 DOTA
JS判断两个时间大小的示例代码
2014/01/28 Javascript
javascript文件中引用依赖的js文件的方法
2014/03/17 Javascript
DOM基础教程之模型中的模型节点
2015/01/19 Javascript
AngularJS基础知识笔记之表格
2015/05/10 Javascript
利用Angularjs和bootstrap实现购物车功能
2016/08/31 Javascript
vue.js 上传图片实例代码
2017/06/22 Javascript
angular中实现li或者某个元素点击变色的两种方法
2017/07/27 Javascript
JS非空验证及邮箱验证的实例
2017/08/11 Javascript
JavaScript原型对象、构造函数和实例对象功能与用法详解
2018/08/04 Javascript
微信小程序实现蒙版弹窗效果
2018/11/01 Javascript
vue组件之间通信方式实例总结【8种方式】
2019/02/22 Javascript
VUE 组件转换为微信小程序组件的方法
2019/11/06 Javascript
js生成1到100的随机数最简单的实现方法
2020/02/07 Javascript
react使用antd表单赋值,用于修改弹框的操作
2020/10/29 Javascript
Vue中computed和watch有哪些区别
2020/12/19 Vue.js
深入理解Python中装饰器的用法
2016/06/28 Python
浅谈Python2.6和Python3.0中八进制数字表示的区别
2017/04/28 Python
python发送邮件实例分享
2017/07/28 Python
Python 利用内置set函数对字符串和列表进行去重的方法
2018/06/29 Python
Python正则表达式实现简易计算器功能示例
2019/05/07 Python
用python打印菱形的实操方法和代码
2019/06/25 Python
Django ORM 查询表中某列字段值的方法
2020/04/30 Python
Python虚拟环境库virtualenvwrapper安装及使用
2020/06/17 Python
CSS3 伪类选择器 nth-child()说明
2010/07/10 HTML / CSS
会议活动邀请函
2014/01/27 职场文书
数控专业自荐书范文
2014/03/16 职场文书
民生工作实施方案
2014/05/31 职场文书
离婚协议书怎么写的
2014/12/14 职场文书
《火纹风花雪月无双》预告“神秘雇佣兵” 紫发剑客
2022/04/13 其他游戏