jQuery使用animate创建循环

jQuery create loop with animate

本文关键字:循环 创建 animate 使用 jQuery      更新时间:2024-02-03

我正试图将一个div向右滑动并使其循环。下面是我的代码jsfiddle的链接:

<head>
  <meta charset="utf-8">
  <title>animate demo</title>
  <style>
  div {
    background-color: #bca;
    width: 100px;
    border: 1px solid green;
  }
  </style>
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>

<div id="block">Hello!</div>
<script>
function scroll() {
    $( "#block" ).animate({marginLeft: "0.6in"}, 
    {
        duration: 1500,
        complete: function() {
            scroll
        }
    }
)};
scroll();
</script>

http://jsfiddle.net/ZWSPJ/

更新:

我很感激你的接受,但adeneo的回答要优雅得多。当他删除它时,我将在这里包括他的轮换方法:现场演示(点击)。

var $block = $('#block'); //I like to cache my references in advance
var flag = 0;
(function scroll() { //auto call this function with an IIFE
  $block.animate({marginLeft: (flag) ? 0 : '0.6in'}, 1500, scroll);
  flag ^= 1; //reverse flag
}());

其他方法:

现场演示(点击)。

var $block = $('#block'); //you can go ahead and cache this reference
function scroll() {
  $block.css('marginLeft', 0); //reset margin
  $block.animate({marginLeft: "0.6in"}, //animate margin
  {
    duration: 1500,
    complete: function() {
      scroll(); //repeat
    }
  }
)};
scroll(); //call function to begin loop

如果你想在每次跑步时反转动画,你可以这样做:

现场演示(点击)。

var $block = $('#block'); //you can go ahead and cache this reference
var animSwitch = 0;
function scroll() {
  var margin = 0;
  if (!animSwitch) {
    margin = '0.6in';
    animSwitch = 1;
  }
  else {
    animSwitch = 0;
  }
  $block.animate({marginLeft: margin}, //animate margin
    {
      duration: 1500,
      complete: function() {
        scroll(); //repeat
      }
    }
  )
};
scroll(); //call function to begin loop

所以一个正确的答案是:

function scroll() {
    $( "#block" ).animate({marginLeft: "+=0.6in"}, 
    {
        duration: 1500,
        complete: scroll
    }
)};
scroll();

你想要这样的东西吗?

小提琴演示

function scroll() {
    $("#block").animate({
        marginLeft: "+=0.6in"
    }, {
        duration: 1500,
        complete:scroll
    })
};
scroll();

问题的一部分是

complete: function() {
    scroll
}

这不会调用滚动函数,只调用包装函数。你需要做:

complete: function() {
    scroll();
}

或更整洁的

complete : scroll