移动端的事件

2016-11-21  本文已影响0人  楚乌

移动端视窗

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
说明

移动端的事件绑定

移动端的事件绑定是通过 ** addEventListener ** 添加

移动端的事件

  1. touchstart: 开始触屏事件 (于手指点击屏幕开始,触屏事件将会有300ms的延迟,因为这样可以判定它是否有第二次点击)

  2. touchmove: 移动事件 (手指在屏幕移动,在这里可以判断移动)

  3. touchend : 结束事件 (手指离开屏幕,结束可以判定与touchstart开始的距离)

  4. touchcancel : 中止事件 (在手机中,接听电话的优先级最高,所以在手机在进行其他操作时,就需要用到该属性)

那么这些属性我们需要从哪里获取呢?

我们可以在事件中传参e来看看

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <title>测试</title>
    <style>
        .div1{
            height: 300px;
            width: 300px;
            background-color: red;
        }
    </style>
</head>
<body>
    <div class="div1"></div>
    <script>
        var div1 = document.querySelector(".div1");

        // 绑定开始触摸事件
        div1.addEventListener('touchstart',function(e){
            console.log(e);
                })
      </script>
测试.jpg

其中我们可以看见changeTouches和targetTouches属性,那么就可见看看其中的值:

changedtouches.jpg targettouches.jpg

在其中我们可以看见点击时的位置以及离开时的距离,其中targetTouches为开始点击屏幕的属性,而changedTouches为离开屏幕的属性,那么我们就可以进行一些最基本的操作,例如:div的移动

<!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">
    <title>拖拽</title>
    <style>
        .div1{
            height: 200px;
            width: 200px;
            background-color: green;
            position: absolute;
        }
    </style>
</head>
<body>
    <div class="div1"></div>
    <script>
        var div = document.querySelector(".div1");
        div.addEventListener('touchstart',function(e){
            var left = e.targetTouches[0].pageX - this.offsetLeft;
            var top = e.targetTouches[0].pageY - this.offsetTop;
            div.addEventListener('touchmove',function(e){
                var touches = e.targetTouches;
                var touch = touches[0];
                this.style.left = touch.pageX - left + 'px';
                this.style.top = touch.pageY - top + 'px';

            })
        })
    </script>
</body>
</html>
上一篇 下一篇

猜你喜欢

热点阅读