首页 > 解决方案 > How to remove touch offset on webpage?

问题描述

I'm experimenting with some touch integration with my web app and i'm noticing that with the code posted below the block that moves on touch has a costant offset and I can temporarly remove it by going in f11 mode. How do i remove it such that the block is always under the finger?

<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<meta name="viewport" 
    content="width=device-width, initial-scale=1.0, user-scalable=no">
<head>
<title>A title</title>
</head>
<style>
body {
    width: 100vw;
    height: 100vh;
    position: absolute;
    top: -8px;
    left: -8px;
    overflow: hidden;
}

</style>
<body>
<div id="bup" style="position:absolute; background-color:blue;width:100px;height:100px;"></div>

<script>
var touch = [];

document.body.addEventListener('touchmove', function(event) {
    event.preventDefault();
    touch = event.touches;
    document.getElementById('bup').style.top= (touch[0].screenY-50) + 'px';
    document.getElementById('bup').style.left= (touch[0].screenX-50) + 'px';
}, false); 
</script>
</body>
</html>

(the -50 is there just to center the block on my finger considering that the block it self is 100x100px)

ty

标签: javascripthtmltouch

解决方案


Alright i solved it my self. the issue was the touch[0].screenX. I shoud have used touch[0].clientX, same for the Y.

Hope this helps someone, see ya


推荐阅读