如何在HTML画布或Div标签内放置jQuery动画对象? 我有图像,可以通过单击按钮向右,向左,向上,向下移动。 以下是我迄今为止所做的工作:
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#moveleft').click(function() {
$('#textbox').animate({
'marginLeft' : "-=80px" //moves left
});
});
$('#moveright').click(function() {
$('#textbox').animate({
'marginLeft' : "+=80px" //moves right
});
});
$('#movedown').click(function() {
$('#textbox').animate({
'marginTop' : "+=80px" //moves down
});
});
$('#moveup').click(function() {
$('#textbox').animate({
'marginTop' : "-=80px" //moves up
});
});
});
</script>
<div style="border:1px solid #c3c3c3;>
<div style="padding:20px;">
<button id="moveleft">Move Left</button>
<button id="moveright">Move right</button>
<button id="movedown">Move Down</button>
<button id="moveup">Move Up</button></div>
<div id="textbox" style="position:absolute;padding:10px;width:300px;">
<img src="sample.gif">
</div>
<div>
答案 0 :(得分:0)
您需要计算offset
并限制父div中的图像。
以下是left
边框图像限制的示例,为所有边框扩展了类似的逻辑:
$(document).ready(function() {
var parent = $("#parent");
var maxLimits = {
"left": parent.offset().left,
"right": parent.offset().left + 300,
"top": parent.offset().top,
"bottom": parent.offset().top + 100
}
$('#moveleft').click(function() {
if (maxLimits.left > $('img').offset().left - 80) {
$('img').animate({
'marginLeft': "=" + maxLimits.left + "px"
});
} else {
$('img').animate({
'marginLeft': "-=80px" //moves left
});
}
});
$('#moveright').click(function() {
$('img').animate({
'marginLeft': "+=80px" //moves right
});
});
$('#movedown').click(function() {
$('img').animate({
'marginTop': "+=80px" //moves down
});
});
$('#moveup').click(function() {
$('img').animate({
'marginTop': "-=80px" //moves up
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div style="border:1px solid #c3c3c3;>
<div style=" padding:20px; ">
<button id="moveleft">Move Left</button>
<button id="moveright">Move right</button>
<button id="movedown">Move Down</button>
<button id="moveup">Move Up</button></div>
<div id="parent" style="position:absolute;padding:10px;width:300px;height:100px ">
<img height=50px width=50px src="sample.gif ">
</div>
<div>