移动端事件

移动端事件

事件类型

移动端事件列表

  • touchstart 元素上触摸开始时触发

  • touchmove 元素上触摸移动时触发

  • touchend 手指从元素上离开时触发

  • touchcancel 触摸被打断时触发

这几个事件最早出现于IOS safari中,为了向开发人员转达一些特殊的信息。

应用场景

  • touchstart 事件可用于元素触摸的交互,比如页面跳转,标签页切换

  • touchmove 事件可用于页面的滑动特效,网页游戏,画板

  • touchend 事件主要跟 touchmove 事件结合使用

  • touchcancel 使用率不高

注意:

  • touchmove 事件触发后,即使手指离开了元素,touchmove 事件也会持续触发

  • 触发 touchmove 与 touchend 事件,一定要先触发 touchstart

  • 事件的作用在于实现移动端的界面交互

事件绑定

方式一

box.ontouchstart = function(){
   console.log('touch start')
}

方式二

box.addEventListener('touchstart', function(){
console.log('touch start')
})

这里推荐使用第二种,第一种有时会失灵。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }

      #demo {
         100%;
        height: 200px;
        background-color: pink;
      }
    </style>
  </head>
  <body>
    <div id="demo"></div>
    <script>
      //   demo.ontouchstart = function() {
      //     console.log('触摸屏幕开始')
      //   }
      //   demo.ontouchmove = function() {
      //     console.log('触摸屏幕移动')
      //   }
      //   demo.ontouchend = function() {
      //     console.log('触摸屏幕结束')
      //   }
      //   demo.ontouchcancel = function() {
      //     console.log('触摸屏幕中断')
      //   }

      demo.addEventListener('touchstart', function() {
        console.log('手指触摸屏幕了')
      })
    </script>
  </body>
</html>

 

 

 

 

 

 

原文地址:https://www.cnblogs.com/fsg6/p/13599296.html