处理拖动时的速度/惯性

时间:2014-03-29 23:52:15

标签: javascript hammer.js inertia

我在我的Web应用程序中构建了一个垂直滑动的东西,支持Hammer.js的鼠标和触摸拖动事件。在拖动结束时(当用户释放鼠标按钮或将他的手指从屏幕上移开时,a.k.a dragend事件),如果上面的一个接近中间,则移动到中间,反之亦然。

问题是,当用户将鼠标从下向下拖动到上方时触发dragend事件(这意味着上面的一个将移动到中间)如果速度足够高,下面的那个应该移动到中间。如何计算速度是否足够高?

1 个答案:

答案 0 :(得分:0)

我解决了这个问题:

// y is the drag amount

// visible height
var height = $(this).height()

// difference
var diff = (Math.abs(y) % height) / height

// I checked Hammer.js's source. It defines velocity as the change in 16ms.
// So multiplying it by 62.5 gives you the change in 1s. 
// Not sure why I did that, but works pretty well in most situations
var inertia = event.gesture.velocityY * 62.5

if (
    (event.gesture.direction == 'up' && diff + (inertia / height) >= 0.5) ||
    (event.gesture.direction == 'down' && diff - (inertia / height) >= 0.5)
) {

    // show the one below

} else {

    // show the one above

}