两次单击后jQuery动画不起作用

djm*_*ank 6 html javascript css jquery jquery-animate

我正在尝试通过jQuery处理动画,我遇到了一个问题,即div框只能工作2次.任何形式的帮助表示赞赏.这是我的代码:

$(document).ready(function() {
  $("#one").click(function() {
    $("div").animate({
      top: '250px'
    });
  });

  $("#sec").click(function() {
    $("div").animate({
      bottom: '250px'
    });
  });

  $("#thi").click(function() {
    $("div").animate({
      right: '250px'
    });
  });

  $("#for").click(function() {
    $("div").animate({
      left: '250px'
    });
  });
});
Run Code Online (Sandbox Code Playgroud)
.box {
  background: grey;
  height: 20px;
  width: 20px;
  position: absolute;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="one">DOWN</button>
<button id="sec">TOP</button>
<button id="thi">LEFT</button>
<button id="for">RIGHT</button>

<br><br>
<div class="box">
</div>
Run Code Online (Sandbox Code Playgroud)

这是我的代码链接:https://jsfiddle.net/djmayank/mcutmbcy/1/

Zak*_*rki 4

更新了小提琴

top/right您可以使用+=和“增加/减少”偏移量-=

$(function(){
    $("#one").click(function(){
        $("div").animate({top: '+=25px'});
    });
    $("#sec").click(function(){
        $("div").animate({top: '-=25px'});
    });
    $("#thi").click(function(){
        $("div").animate({right: '+=25px'});
    });
    $("#for").click(function(){
        $("div").animate({right: '-=25px'});
    });
});
Run Code Online (Sandbox Code Playgroud)

注意:您可以只使用一种ready功能。

希望这可以帮助。

$(function(){
    $("#one").click(function(){
        $("div").animate({top: '+=25px'});
    });
    $("#sec").click(function(){
        $("div").animate({top: '-=25px'});
    });
    $("#thi").click(function(){
        $("div").animate({right: '+=25px'});
    });
    $("#for").click(function(){
        $("div").animate({right: '-=25px'});
    });
});
Run Code Online (Sandbox Code Playgroud)
$(document).ready(function(){
  $("#one").click(function(){
      $("div").animate({top: '+=100px'});
  });
  $("#sec").click(function(){
      $("div").animate({top: '-=100px'});
  });
  $("#thi").click(function(){
      $("div").animate({right: '+=100px'});
  });
  $("#for").click(function(){
      $("div").animate({right: '-=100px'});
  });
});
Run Code Online (Sandbox Code Playgroud)
.box{
  background:grey;
  height:20px;
  width:20px;
  position:absolute;
}
Run Code Online (Sandbox Code Playgroud)