Simulate arrow keys on mobile phone 手机上模拟键盘的上下左右按钮

    <textarea placeholder="test touchmove" ontouchstart="onTouchStart(event)" ontouchmove="onTouchMove(event)" ontouchend="onTouchEnd(event)"></textarea>

    <script type="text/javascript">
        // https://hangj.cnblogs.com
        let identifier = null
        let touchTarget = null
        let touchStartX = null
        let touchStartY = null
        let touchNowX = null
        let touchNowY = null
        let touchTimestamp = null
        let intervalID = null

        function onTouchStart(event) {
            if (identifier != null) return;

            let touch = event.targetTouches[0]
            identifier = touch.identifier
            touchTarget = touch.target
            touchStartX = touch.clientX
            touchStartY = touch.clientY
            touchNowX = touchStartX
            touchNowY = touchStartY
            touchTimestamp = new Date().getTime()

            if (intervalID) clearInterval(intervalID);
            intervalID = setInterval(()=>{
                if (identifier == null) {
                    if (intervalID) clearInterval(intervalID);
                    intervalID = null
                }
                const x = touchNowX > touchStartX ? 'right' : 'left'
                const y = touchNowY > touchStartY ? 'down' : 'up'
                console.log(x, y)
            }, 200)
        }
        function onTouchEnd(event) {
            if (identifier == null) return;

            for (let i=0; i < event.changedTouches.length; i++) {
                if (event.changedTouches.item(i).identifier == identifier) {
                    identifier = null
                    return
                }
            }
        }
        function onTouchMove(event) {
            if (identifier == null) return;
            event.preventDefault()

            let touch = null
            for (let i=0; i < event.changedTouches.length; i++) {
                if (event.changedTouches.item(i).identifier == identifier) {
                    touch = event.changedTouches.item(i)
                    break
                }
            }
            if (!touch) return;

            touchNowX = touch.clientX
            touchNowY = touch.clientY
        }
    </script>

posted on 2023-03-08 15:02  明天有风吹  阅读(65)  评论(0编辑  收藏  举报

导航

+V atob('d2h5X251bGw=')

请备注:from博客园