我想知道是否有人可以帮助我。我仍在学习jQuery,但我不明白为什么“向左”和“向上”按钮不起作用。它完美地落下。这是我的代码:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#dolu").click(function(){
$("div").animate({
marginTop:"100px"
}, "slow");
});
});
$(document).ready(function(){
$("#desno").click(function(){
$("div").animate({
marginLeft:"100px"
}, "slow");
});
});
$(document).ready(function(){
$("#gore").click(function(){
$("div").animate({
marginBottom:"100px"
}, "slow");
});
});
$(document).ready(function(){
$("#levo").click(function(){
$("div").animate({
marginRight:"100px"
}, "slow");
});
});
</script>
</head>
<body>
<button id="gore">Up</button>
<button id="dolu">Down</button>
<button id="levo">Left</button>
<button id="desno">Right</button><br><br>
<div id="kocka" style="width:50px; height:50px; background-color:#D0D0D0; opacity:1"></div>
</body>
</html>
答案 0 :(得分:1)
您要设置不影响头寸的边距。在有足够空间的地方放置右边距不会对左边位置产生任何影响。而是改回左边距,从现有的左边距或减去100。
答案 1 :(得分:0)
您将要使用String值进行相对运动。也仅参考marginTop
和marginLeft
$(function() {
var k = $("div#kocka");
$("#dolu").click(function() {
k.animate({
marginTop: "+=100px"
}, "slow");
});
$("#desno").click(function() {
k.animate({
marginLeft: "+=100px"
}, "slow");
});
$("#gore").click(function() {
k.animate({
marginTop: "-=100px"
}, "slow");
});
$("#levo").click(function() {
k.animate({
marginLeft: "-=100px"
}, "slow");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<button id="gore">Up</button>
<button id="dolu">Down</button>
<button id="levo">Left</button>
<button id="desno">Right</button><br><br>
<div id="kocka" style="width:50px; height:50px; background-color:#D0D0D0; opacity:1">
</div>
参考:Moving from position A to position B slowly with animation