gpt4 book ai didi

javascript - 鼠标速度javascript函数

转载 作者:行者123 更新时间:2023-11-30 12:54:18 25 4
gpt4 key购买 nike

正在处理一些 javascript。我找到了一个非常好的函数来计算光标的速度。问题是我想返回实际值,而不是回调。你会怎么做?

        function makeVelocityCalculator(e_init, callback) {
var x = e_init.clientX,
y = e_init.clientY,
t = Date.now();
return function(e) {
var new_x = e.clientX,
new_y = e.clientY,
new_t = Date.now();
var x_dist = new_x - x,
y_dist = new_y - y,
interval = new_t - t;
// update values:
x = new_x;
y = new_y;
t = new_t;
var velocity = Math.sqrt(x_dist*x_dist+y_dist*y_dist)/interval;
callback(velocity);
};
}

最佳答案

好吧,然后更改该函数以返回速度,而不是“回调(速度)”

Js Fiddle sample

或者你可以按照预期的方式使用它

makeVelocityCalculator(initialEvent, function(velocity) {
console.log("velocity is", velocity);
});
is pretty much same as
var velocity = makeVelocityCalculator(initialEvent);
console.log("velocity is", velocity);

关于javascript - 鼠标速度javascript函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19794323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com