gpt4 book ai didi

javascript - jquery ui 拖动缓动/惯性

转载 作者:数据小太阳 更新时间:2023-10-29 05:39:53 29 4
gpt4 key购买 nike

使用 jquery ui draggable (http://jqueryui.com/demos/draggable/) 拖动元素时如何启用缓动或惯性?我想重新创建类似于 maps.google.com 的缓动,当你扔/拖动 map 时它会缓动到位。理想情况下,我想根据您 throw /拖动元素的力来移动元素。你如何实现这个功能?也许 jquery ui draggable 不是必需的,但我希望模拟 Google map 上的拖动和缓动。

谢谢!

最佳答案

我使用了 here 中的一些想法但将它们与 jQuery UI 集成在一起。您必须实现逻辑来处理将元素推出边界(超出其父容器边界)的动量动画

结果代码:

$(function() {
var $d = $("#draggable");

var x1, x2,
y1, y2,
t1, t2; // Time

var minDistance = 40; // Minimum px distance object must be dragged to enable momentum.

var onMouseMove = function(e) {
var mouseEvents = $d.data("mouseEvents");
if (e.timeStamp - mouseEvents[mouseEvents.length-1].timeStamp > 40) {
mouseEvents.push(e);
if (mouseEvents.length > 2) {
mouseEvents.shift();
}
}
}

var onMouseUp = function() {
$(document).unbind("mousemove mouseup");
}

$d.draggable({
start: function(e, ui) {
$d.data("mouseEvents", [e]);
$(document)
.mousemove(onMouseMove)
.mouseup(onMouseUp);
},
stop: function(e, ui) {
$d.stop();
$d.css("text-indent", 100);

var lastE = $d.data("mouseEvents").shift();

x1 = lastE.pageX;
y1 = lastE.pageY;
t1 = lastE.timeStamp;
x2 = e.pageX;
y2 = e.pageY;
t2 = e.timeStamp;

// Deltas
var dX = x2 - x1,
dY = y2 - y1,
dMs = Math.max(t2 - t1, 1);

// Speeds
var speedX = Math.max(Math.min(dX/dMs, 1), -1),
speedY = Math.max(Math.min(dY/dMs, 1), -1);

// Distance moved (Euclidean distance)
var distance = Math.sqrt(Math.pow(x1-x2, 2) + Math.pow(y1-y2, 2));

if (distance > minDistance) {
// Momentum
var lastStepTime = new Date();
$d.animate({ textIndent: 0 }, {
duration: Math.max(Math.abs(speedX), Math.abs(speedY)) * 2000,
step: function(currentStep){
speedX *= (currentStep / 100);
speedY *= (currentStep / 100);

var now = new Date();
var stepDuration = now.getTime() - lastStepTime.getTime();

lastStepTime = now;

var position = $d.position();

var newLeft = (position.left + (speedX * stepDuration / 4)),
newTop = (position.top + (speedY * stepDuration / 4));

$d.css({
left: newLeft+"px",
top: newTop+"px"
});
}
});
}
}
});
});

Try it out

关于javascript - jquery ui 拖动缓动/惯性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4443526/

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