div boundary jQuery
http://jsbin.com/ofudi4/3/edit
What this code does you can test for yourselves.
Now my question is if i would have another div-tag around , like a frame. How would i make #moveMe to just move inside the frame div? Checking for boundaries after each move, so the figure doesn't move outside the frame.
Anyone now how to?
EDIT: Adding code from link.
$(document).keydown(function(e){
// Le开发者_如何学Pythonft
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;
}
});
HTML
<body>
<div id="moveMe"></div>
</body>
if you change from animating margin to animating left and top it's easier test conditions using .position()
test if it's less than zero or greater than the parent width/height - it's width/height.
if not, animate as usual, if so set to to the edge.
You should also look into changing the easing, the movement is a bit odd when you hold it down.
if (e.keyCode == 37) {
if($("#moveme").position().left >= 100)
{
$("#moveMe").animate({left: "-=100px"}, {queue:false});
}
else
{
$("#moveMe").animate({left: 0}, {queue:false});
}
return false;
}
if (e.keyCode == 39) {
if($("#moveMe").position().left <=
$("#moveMe").parent().width() - $("#moveMe").width() - 100)
{
$("#moveMe").animate({left: "+=100px"}, {queue:false});
}
else
{
$("#moveMe").animate(
{left: $("#moveMe").parent().width() - $("#moveMe").width()},
{queue:false});
}
return false;
}
http://jsbin.com/ofudi4/5
精彩评论