您的位置:首页 > Web前端 > JavaScript

js基本touch事件

2015-08-06 15:11 519 查看
正常情况下,一次触摸会按照这样的顺序触发事件:

touchstart

mousedown

touchmove

mousemove

touchend

mouseup

click

可以使用e.preventDefault()阻止事件冒泡

例子:

光点跟随手指移动

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width , initial-scale=1 , maximum-scale=1 , user-scalable=no">

<style>

body{background-color:#222;}

.spot{position:absolute; width:70px; height:70px; border-radius:35px; box-shadow:0px 0px 40px #fff; background-color:#fff; opacity:.7;}

</style>

</head>

<body>

<script>

var spot = null;

document.addEventListener('touchstart',function(e){

    //touch所有类型事件都会冒泡,如果阻止了touchstart的默认行为,后续的mousedown和click事件将不会触发

    e.preventDefault();

    //如果已经生成小光点了,就直接返回

    if(spot){

        return;

    }

    spot = document.createElement('div');

    spot.classList.add('spot');

    spot.style.top = e.touches[0].pageY - 35;

    spot.style.left = e.touches[0].pageX - 35;

    document.body.appendChild(spot);

},false);

document.addEventListener('touchmove',function(e){

    //阻止了touchmove的默认行为,后续的mousemove事件将不会触发

    e.preventDefault();

    if(spot){

        spot.style.top = e.touches[0].pageY - 35;

        spot.style.left = e.touches[0].pageX - 35;

    }

});

document.addEventListener('touchend',function(e){

    //如果阻止了touchend的默认行为,后续的mouseup和click事件将不会触发

    e.preventDefault();

    if(spot){

        //删除这个光点

        document.body.removeChild(spot);

        spot = null;

    }

})

</script>

</body>

</html>

注意:

touches表示当前位于屏幕上的所有手指动作的列表,是一个TouchList类型的对象,TouchList是一个类数组对象,它里面装的是Touch对象

关于坐标:

clientX/Y:触摸点相对于浏览器窗口viewport的位置

pageX/Y:触摸点相对于页面的位置

screenX/Y:触摸点相对于屏幕的位置--通常来说和clientX/Y在计算时的区别就是少了一个状态栏和地址栏
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: