【问题标题】:jQuery animation on multiple elements, single animation thread/timer or multiple?多个元素上的jQuery动画,单个动画线程/计时器还是多个?
【发布时间】:2010-09-02 22:41:28
【问题描述】:

我想知道 jQuery 选择器何时返回多个元素,例如我对所有这些元素执行“slideDown”...

$('.allthisclasss').slideDown();

是否有一个代码循环可以同步向下移动所有对象,或者 jQuery 是否分别处理所有对象并且它们每个都有一个执行线程来移动自己?

我的问题是关于动画优化的,如果所有对象只有一个计时器而不是每个对象一个,那就太好了。

有人知道 jQuery 是如何处理这种情况的吗?

【问题讨论】:

  • 你看过源代码吗?
  • 我看了看,看到了下面的队列..但甚至没有看到“setTimeout”或“setIterval”......明天我会更深入地挖掘。
  • 我使用了装饰器模式来找出答案。看看我的答案。 jQuery 非常优化。

标签: javascript jquery optimization animation


【解决方案1】:

所有动画都会自动添加到 jQuery 中的全局效果队列中。但这并不意味着它们是按顺序制作的,制作一个简单的测试页面,其中包含十个元素,你们都可以同时滑动。您会看到它们是同时执行的。

为了防止这种行为,您可以创建自己的队列,queue documentation 中的示例对此进行了最佳描述

黑客愉快!

【讨论】:

  • 我在说动画是同步的。同一队列中的每个元素是否都有自己的动画循环?就像 4 个移动对象有它们的 4 个循环/计时器并行运行以驱动它们自己的对象..
  • 我认为这是一个正确的假设,但请尝试并告诉我们°-)
  • 我使用了装饰器模式来找出答案。看看我的答案。 jQuery 非常优化:)
【解决方案2】:

我终于有了答案:只有一个计时器可以为页面中的所有内容设置动画。如果队列中有东西,则会创建一个计时器来移动所有内容,一旦所有内容完成,计时器就会被终止:

使用的 HTML:

<div id="test1" class="tests" style="background-color:#FFF; border:1px solid #000; width:40px; height:40px; position:absolute; left:0px; top:0px;"></div>
<div id="test2" class="tests" style="background-color:#FFF; border:1px solid #000; width:40px; height:40px; position:absolute; left:0px; top:50px;"></div>

使用的 JavaScript:

var setIntervalDecorated = setInterval;
setInterval = function(func, delai) {
    var id = setIntervalDecorated(func, delai);
    console.log('setInterval: ' + id + ' (' + delai + 'ms)');
    return id;
};

var clearIntervalDecorated = clearInterval;
clearInterval = function(id) {
    console.log('clearInterval: ' + id);
    clearIntervalDecorated(id);
};

测试用例:

测试 1

$('#test1').animate({ left: '+=500' }, 5000, function() { console.log('test1: Animation complete'); });

setInterval: 5 (13ms)
test1: Animation complete
clearInterval: 5

测试 2

$('.tests').animate({ left: '+=500' }, 5000, function() { console.log('tests: Animation complete'); });

setInterval: 5 (13ms)
tests: Animation complete
tests: Animation complete
tests: Animation complete
clearInterval: 5

测试 3

$('#test1').animate({ left: '+=500' }, 5000, function() { console.log('test1: Animation complete'); });
$('#test2').animate({ left: '+=500' }, 5000, function() { console.log('test2: Animation complete'); });

setInterval: 5 (13ms)
test1: Animation complete
test2: Animation complete
clearInterval: 5

测试 4

$('#test1').animate({ left: '+=500' }, 5000, function() { console.log('test1: Animation complete'); });
setTimeout(function() { $('#test2').animate({ left: '+=500' }, 5000, function() { console.log('test2: Animation complete'); }); }, 1000);

setInterval: 5 (13ms)
test1: Animation complete
test2: Animation complete
clearInterval: 5

谢谢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-02
    • 2020-03-23
    相关资源
    最近更新 更多