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>
+V why_null 请备注:from博客园