jQuery animate 循环卡在第一个循环中

jQuery animate loop stuck in first loop

本文关键字:循环 第一个 animate jQuery      更新时间:2023-09-26

我正在尝试在jQuery上做一个简单的动画。这个想法是将图像向右移动,然后回到开始的位置。

A 编写了以下代码:

function logo(img) {
    $(img).animate( {
       left: 100
    }, 900, function() {
       $(img).animate({
          left: 0,
       }, 900,  logo(img))
    })
}    

而这个 HTML

<div style="position: relative; width:500px; height: 55px; overflow: visible;">
<img class="pena" src="https://www.google.com.br/images/srpr/logo11w.png" width="50px" style="position: absolute; left: 0px; top: 0;" onclick="logo(this);">
</div>

http://jsfiddle.net/rtfmu5za/1/

但是在动画运行的第一时间,她卡住了一段时间。之后,一切正常。

我错了什么?

你的代码确实有一个奇怪的问题,我无法真正解释为什么会发生这种情况。试试这个解决方案,对我有用:

var position = 0;
function logo(img) {
    position = position == 0 ? 100 : 0;
    $(img).animate( {
        left: position
    }, 900, function () { logo(this) });
}

http://jsfiddle.net/oqLakcbj/