jQuery简单的左右动画

时间:2011-05-22 05:00:20

标签: jquery jquery-animate

我希望箭头能够明显地移动到数字上并在返回途中删除文本。

http://jsfiddle.net/mplungjan/VZsG4/

<span class="arrow">&rarr;</span>&nbsp;&nbsp;&nbsp;&nbsp;<span id="span0">zhong</span><span id="span2">1</span><span id="span3">guo</span><span id="span4">2</span>
<br />
<input type="button" id="start" value="start" />
<input type="button" id="reset" value="reset" />

var cnt = 0;
var spanLength = $("span").length;
$("#start").click(function() {
  var tId = setInterval(
    function() {
      if (cnt>spanLength-1) clearInterval(tId);
      $(".arrow").animate(
        {"right": $("#span"+(cnt+1)).position()}, "slow",
          function(){
            $("#span"+(cnt++)).hide(); // remove word
            $("#span"+(cnt++)).hide(); // remove number
            $(".arrow").animate({"left":0}); // move back
          }
      );
    },
  1000);  
});
$("#reset").click(function() {
    clearInterval(tId);
    $("span").each(function() {
        $(this).show();
    });    
});

1 个答案:

答案 0 :(得分:6)

您的代码存在一些问题:

  • .arrow需要使用position:relative
  • 的CSS
  • 您需要在箭头
  • 上为left而不是right制作动画
  • 您需要获取left
  • position()属性
  • var tId需要处于更广泛的范围内
  • 由于.arrow是一个范围,因此间隔从未被清除
  • 您跳过导致缺少元素错误的#span1
  • cnt = 0需要添加到重置功能

See working fiddle here →

var cnt = 0;
var spanLength = $("span").length;
var tId;
$("#start").click(function() {
  tId = setInterval(
    function() {
        if (cnt>=spanLength-1) {
            clearInterval(tId);
        } else {
          $(".arrow").animate(
            {"left": $("#span"+(cnt+1)).position().left}, "slow",
              function(){
                $("#span"+(cnt++)).hide(); // remove word
                $("#span"+(cnt++)).hide(); // remove number
                $(".arrow").animate({"left":0}); // move back
              }
          ); 
        }
    },
  1000);  
});
$("#reset").click(function() {
    clearInterval(tId);
    cnt = 0;
    $("span").each(function() {
        $(this).show();
    });    
});