繁体   English   中英

多元素jQuery动画问题

[英]Multi-element jQuery animation issue

我试图遍历动画,选择多个元素并移动它们,只要鼠标悬停在父区域上即可。 这足够好,但是每次动画循环遍历第一个元素(子元素)时,移动速度都比其他元素快。 ??? JSFiddle示例

HTML:

<div id="menuContent">
    <button id="btn1" class="mainButton" left="0"/>
    <button id="btn2" class="mainButton" left="0"/>
    <button id="btn3" class="mainButton" left="0"/>
</div>

jQuery的:

$("#menuContent").hover(function () {
    loop();
    }
    , function () {
        stop();
    }
);

function stop() {
    $(".mainButton").stop();
}

    function loop() {
   $(".mainButton").stop().animate({ left: "+=20"}, 100, 'linear', function () { loop(); });
}

从文档中:

完成

动画完成后调用的函数,每个匹配元素调用一次。

调用animate它将启动3个动画。 第一个元素的动画首先开始和完成。 然后调用它的complete动画,然后停止并启动所有动画,尽管其中一些动画尚未完成。

考虑以下示例( 小提琴 ):

function loop() {
  $('.mainButton').stop().animate({
    left: '+=1'
  }, 1, 'linear', function() {
    loop();
  });
}

只有一个圈会移动,因为其他人没有移动的时间间隔。

您可以使用Promise使其工作( Fiddle ):

$('#menuContent').hover(function() {
  $('.mainButton').data('run', true);
  loop();
}, function() {
  $('.mainButton').data('run', false);
});

function loop() {
  if (!$('.mainButton').data('run')) return;
  $('.mainButton').animate({left: '+=10'}, 100, 'linear').promise().done(loop);
}

Danil Speransky是正确的。 但是,animate函数有一个options参数,以允许动画不在严格的队列中运行。

`$(".mainButton").animate({ left: "+=20"},{queue: false}, 100, 'linear', function () { loop();});`

在此处查看queue:false的文档。

您的里程可能会有所不同,但是执行以下两项操作似乎很有帮助:

首先,为.mainButton元素存储jQuery对象:

var $mainButton = $('.mainButton')

其次,增加left增量并增加延迟:

$mainButton.stop().animate(
  { left: "+=1000"},
  5000,
  'linear', 
  function() { loop() })

您可以用更多的数字来模拟,看看是否能获得更好的性能。

https://jsfiddle.net/wotfLyuo/8/

如果jquery集合中一个元素的动画完成,则将调用完整的处理程序。 因此,当第一个元素完成时,您将调用loop并停止其他元素的动画。 更好地使用promise and done,并将动画状态保存在集合中:

$("#menuContent").hover(function () {
    start();
}, function () {
    stop();
});

function start() {
    $(".mainButton").data('stopped', false);
    loop();
}

function stop() {
    $(".mainButton").data('stopped', true).stop();
}

function loop() {
    var $mainButtons = $(".mainButton").stop();
    if(!$mainButtons.data('stopped'))
        $mainButtons.animate({ left: "+=20"}, 100, 'linear').promise().done(loop);
}

这是一个工作的小提琴( https://jsfiddle.net/wotfLyuo/5/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM