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 相关文章推荐
跨浏览器的 mouseenter mouseleave 以及 compareDocumentPosition的使用说明
May 04 Javascript
js中document.write使用过程中的一点疑问解答
Mar 20 Javascript
使用Jquery获取带特殊符号的ID 标签的方法
Apr 30 Javascript
CSS3实现动态背景登录框的代码
Jul 28 Javascript
js判断当前页面在移动设备还是在PC端中打开
Jan 06 Javascript
浅谈jquery拼接字符串效率比较高的方法
Feb 22 Javascript
jQuery实现页面倒计时并刷新效果
Mar 13 Javascript
深入理解AngularJS中的ng-bind-html指令
Mar 27 Javascript
Vuex之理解state的用法实例
Apr 19 Javascript
使用JS和canvas实现gif动图的停止和播放代码
Sep 01 Javascript
vue router的基本使用和配置教程
Nov 05 Javascript
深入理解es6块级作用域的使用
Mar 28 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
PHP网上调查系统
2006/10/09 PHP
PHP生成带有雪花背景的验证码
2008/09/28 PHP
php array的学习笔记
2012/05/10 PHP
将博客园(cnblogs.com)数据导入到wordpress的代码
2013/01/06 PHP
跟我学Laravel之安装Laravel
2014/10/15 PHP
phpmyadmin中禁止外网使用的方法
2014/11/04 PHP
php实现将任意进制数转换成10进制的方法
2015/04/17 PHP
Docker 如何布置PHP开发环境
2016/06/21 PHP
PHP机器学习库php-ml的简单测试和使用方法
2017/07/14 PHP
在Laravel中使用GuzzleHttp调用第三方服务的API接口代码
2019/10/15 PHP
javascript的函数
2007/01/31 Javascript
JavaScript DOM 添加事件
2009/02/14 Javascript
javascript中负数算术右移、逻辑右移的奥秘探索
2013/10/17 Javascript
js实现的折叠导航示例
2013/11/29 Javascript
javascript日期对象格式化为字符串的实现方法
2014/01/14 Javascript
jQuery中:only-child选择器用法实例
2015/01/03 Javascript
js实现键盘控制DIV移动的方法
2015/01/10 Javascript
JS动画效果打开、关闭层的实现方法
2015/05/09 Javascript
详解js中class的多种函数封装方法
2016/01/03 Javascript
11个教程中不常被提及的JavaScript小技巧(推荐)
2019/04/17 Javascript
[51:06]DOTA2-DPC中国联赛 正赛 Elephant vs Aster BO3 第二场 1月26日
2021/03/11 DOTA
使用Python中的线程进行网络编程的入门教程
2015/04/15 Python
使用Python对IP进行转换的一些操作技巧小结
2015/11/09 Python
浅析Python中的for 循环
2016/06/09 Python
Python模块搜索路径代码详解
2018/01/29 Python
python和shell获取文本内容的方法
2018/06/05 Python
在python带权重的列表中随机取值的方法
2019/01/23 Python
Python3.5迭代器与生成器用法实例分析
2019/04/30 Python
俄罗斯儿童和青少年服装、鞋子及配件的在线商店:Orby
2020/02/20 全球购物
局域网定义和特性
2016/01/23 面试题
幼师自我鉴定范文
2013/10/01 职场文书
三个儿子教学反思
2014/02/03 职场文书
《十六年前的回忆》教学反思
2014/02/14 职场文书
初二学习计划书范文
2014/04/27 职场文书
python基于opencv批量生成验证码的示例
2021/04/28 Python
Apache Hudi集成Spark SQL操作hide表
2022/03/31 Servers