当前位置: 首页 > 工具软件 > DHTMLX Touch > 使用案例 >

js多点触摸touch事件

滑弘扬
2023-12-01
<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 spots = {} , touches , timer;

    document.addEventListener('touchstart',function(e){
        e.preventDefault();
        [].forEach.call(e.targetTouches,function(touch){
            //对每一根触摸在屏幕上的手指都生成一个元素,并且用touch.identifier作为该元素的唯一标识,触摸结束后清除引用的元素
            if(spots[touch.identifier]){
                return;
            }
            var spot = spots[touch.identifier] = document.createElement('div');
            spot.classList.add('spot');
            spot.style.top = touch.pageY - 35;
            spot.style.left = touch.pageX - 35;
            document.body.appendChild(spot);
        })
        timer = setInterval(function() {
            renderTouches(touches);
        },16);
    },false);

    document.addEventListener('touchmove',function(e){
        e.preventDefault();
        touches = e.touches;
    });

    function renderTouches(touches){
        if(!touches){
            return;
        };
        [].forEach.call(touches,function(touch){
            var spot = spots[touch.identifier];
            if(spot){
                spot.style.top = touch.pageY - 35;
                spot.style.left = touch.pageX - 35;
            }
        })
    }

    document.addEventListener('touchend',function(e){
        e.preventDefault();
        [].forEach.call(e.changedTouches,function(touch){
            var spot = spots[touch.identifier];
            if(spot){
                document.body.removeChild(spot);
                delete spots[touch.indentifier];
            }
        })
        if(e.changedTouches.length === 0){
            clearInterval(timer);
        }
    })

    //touches:表示当前位于屏幕上的所有手指动作的列表,是一个TouchList类型的对象,TouchList是一个类数组对象,它里面装的是Touch对象
    //targetTouches:位于当前DOM元素上的手指动作的TouchList列表
    //changedTouches:涉当前事件的手指动作的列表,例如,在一个touchend事件中,这将是移开的那根手指
    //touchstart等事件在触发时是允许多个手指同时触摸屏幕的,每一根手指都会产生一个Touch对象,包含以下属性:identifier一个数字,用于唯一标识触摸会话中的当前手指,target作为动作目标的DOM元素,及坐标相关clientX/Y等


</script>
</body>
</html>
 类似资料: