jQuery - how to move figure in coordinationsystem
Lets say that I have this code:
<div id="gameFrame">
<div id="figure"></div>
</div>
Where the figure div is lets say a picture of a figure. How can i use jQuery in order to mo开发者_Python百科ve the figure inside the gameFrame with the keyboard keys up down left and right?
Take a look at my demo:
$(document).keydown(function(e){
// Left
if (e.keyCode == 37) {
$("#moveMe").animate({marginLeft: "-=100px"}, {queue:false});
return false;
}
// Top
if (e.keyCode == 38) {
$("#moveMe").animate({marginTop: "-=100px"}, {queue:false});
return false;
}
// Right
if (e.keyCode == 39) {
$("#moveMe").animate({marginLeft: "+=100px"}, {queue:false});
return false;
}
// Bottom
if (e.keyCode == 40) {
$("#moveMe").animate({marginTop: "+=100px"}, {queue:false});
return false;
}
});
In your case you would need to check for boundaries after each move, so the figure doesn't move outside the frame.
With the exception of keyboard use, what you are trying to do has already been done in the jQuery Draggable module: http://jqueryui.com/demos/draggable/#default. You might be able to use what they have done their as a start point. The actual code is here: https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.draggable.js.
The downside is that you might have to put considerable effort into extending/modifying the code, and it will still likely depend on other jQuery code.
Then again, you could probably whip something up in a fraction of the size of the jQuery code. But, I thought I'd post this in case no one else turned anything up.
If you want to do it yourself, the general process would be:
- Wrap the item you want to move in a container (like another
div
) and set the position to be relative using CSS. - Bind keyboard events for the arrow keys
- When a key is pressed, modify the positioning of the element to move it (CSS attributes like
left
andtop
)
精彩评论