If I have a div that is a 5x5 square or something. I want to be able to click on it, then while holding down the mouse, move it in a direction, and upon release of the mouse, have the div fly towards the direction i "flicked". How can I accomplish thi开发者_运维知识库s with jquery or javascript? Not sure if an algorithm or logic is behind this.
From a conceptual perspective (I'll be beaten with actual code no doubt shortly) I would register the mouse coordinates on MouseDown, and compare them against the mouse coordinates on MouseUp to determine the angle at which to move the div (this would allow the DIV to continue moving in the correct direction, even when the MouseUp was close to the DIV).
The easier way would be to just move the square towards the MouseUp coordinates (i.e. mouse down coordinates don't really matter in a small DIV), but this doesn't work as well if the MouseUp is very close to the MouseDown.
Either way, use something like this answer (How to make a div or object gradually move to point of mouseclick with javascript?), except on MouseUp/MouseRelease instead of click, ideally towards a projected point (along the line between MouseDown and MouseUp at a specified distance).
Edit
I've included a Prototype example below (it's very rushed and could use plenty of optimisations + clearer concept on the differences between Page/Graph y-axis, as well as some better handling of steep slopes, as well as calculating distance to fling based on distance between mousedown/mouseup as fauxtrot mentions in comments, as well as perhaps disabling fling after the first fling as you can keep "flinging it around" at the moment, as well as "out of bounds" checks and perhaps reverse bouncing off the edges).
Running Example: http://jsfiddle.net/9B9sA/
HTML
<div id="bluebox"
style="width:100px;
height:100px;
background-color:blue;
position:absolute;
left:300px;
top:300px;"> </div>
jQuery (including jQuery UI for animate)
var startDownX, startDownY;
$(document).ready(function() {
/* Stop default Firefox etc. drag */
$(document).bind("dragstart", function() {
return false;
});
/* Capture start of flings */
$('#bluebox').mousedown(function (event) {
startDownX = event.pageX;
startDownY = event.pageY;
});
/* Work out fling direction on end of fling */
$(document).mouseup(function(event){
/* Page y-axis is different from graph */
var rise = -(event.pageY - startDownY);
var run = event.pageX - startDownX;
var newX = $('#bluebox').position().left;
var newY = $('#bluebox').position().top;
var distanceToFling = 100;
if (run == 0 || Math.abs(rise/run) > 3) {
if (rise > 0) {
newY -= distanceToFling;
} else if (rise < 0) {
newY += distanceToFling;
}
}
else {
if (run > 0) {
newX += distanceToFling;
newY -= (rise/run) * distanceToFling;
}
else {
newX -= distanceToFling;
newY += (rise/run) * distanceToFling;
}
}
$('#bluebox').animate({
left: newX,
top: newY
}, 1000);
}); });
Jquery is your friend, here is a good plugin, check it out
精彩评论