美文网首页
移动端的事件

移动端的事件

作者: 楚乌 | 来源:发表于2016-11-21 20:44 被阅读0次

    移动端视窗

    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
    说明
    • width=device-width 应用程序的宽度和屏幕的宽度是一样的

    • initial-scale=1.0 应用程序启动时候的缩放尺度(1.0表示不缩放)

    • user-scalable=no/0 //用户是否可以通过他的手势来缩放整个应用程序,使应用程序的尺度发生一个改变 (no 和 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>
    

    相关文章

      网友评论

          本文标题:移动端的事件

          本文链接:https://www.haomeiwen.com/subject/wmnupttx.html