是否可以将第一个 pageX 值存储在 touchstart 上?
我想计算 touchstart 的初始值和 touchmove 的实际值之间的距离。
例如:
我触摸屏幕:startX = 100; 然后,我在屏幕上移动手指:moveX = 150;
startX与moveX的距离为(moveX - startX) = 50;
代码更新:
function touch(event) {
var moveX = event.pageX;
var totalMoved = Math.abs(document.startX - moveX);
shipX = totalMoved;
consoleLog(totalMoved);
};
function touchStart(event) {
touch(event.touches[0]);
document.startX = event.pageX;
};
function touchMove(event) {
event.preventDefault();
touch(event.touches[0]);
};
function touchEnd(event) {
touch(event.touches[0]);
var totalMoved = 0;
};
I want to calculate the distance between the initial value of the touchstart and the actual value on touchmove.
for exemple :
I touch the screen : startX = 100;
Then, I move my finger on the screen : moveX = 150;
The distance from startX and moveX is (moveX - startX) = 50;
CODE UPDATED :
function touch(event) {
var moveX = event.pageX;
var totalMoved = Math.abs(document.startX - moveX);
shipX = totalMoved;
consoleLog(totalMoved);
};
function touchStart(event) {
touch(event.touches[0]);
document.startX = event.pageX;
};
function touchMove(event) {
event.preventDefault();
touch(event.touches[0]);
};
function touchEnd(event) {
touch(event.touches[0]);
var totalMoved = 0;
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,这是可能的。您只需将该值存储在
touchMove()
函数中可见的范围内即可。为了便于说明,我们可以通过污染全局作用域来解决这个问题:当然,有多种方法可以在不污染全局作用域的情况下做到这一点。例如,您可以使事件处理函数成为某个对象的成员,该对象将必要的状态作为成员变量保存。或者,
touchStart()
处理程序可以创建一个封装startX
变量的闭包,然后将其设置为touchesMoved
处理程序。等等。Yes, this is possible. You just need to store the value in a scope that will be visible in your
touchMove()
function. For the sake of illustration, we can solve this problem by polluting the global scope:Of course, there are various ways to do this without polluting the global scope. For instance, you could make your event handler functions be members of some object that holds the necessary state as member variables. Or the
touchStart()
handler could create a closure that encapsulates thestartX
variable and then set that to be thetouchesMoved
handler. And so on.moveX 在不同的函数中声明,因此表示不同的变量。相反,在所有这些函数的封闭范围内声明
var moveX
(我猜您可能希望对startX
执行相同的操作)。You
moveX
s are declared in different functions and hence denote different variables. Declarevar moveX
in the enclosing scope for all these functions instead (I guess you might want to do the same withstartX
).