【问题标题】:Is it okay to use .animate with 0 duration all the time? Is there a better alternative?可以一直使用 0 持续时间的 .animate 吗?有更好的选择吗?
【发布时间】:2013-07-16 21:51:55
【问题描述】:

我已经习惯通过执行以下操作来编写我的 jquery 动画。

  1. 使用 css 或 javascript 设置元素的初始状态(宽度、高度、顶部、左侧、不透明度等)。这个初始状态是动画结束的状态。

  2. 使用持续时间为 0 的 .animate 将元素移动到元素处于动画开头的状态。

  3. 使用具有适当持续时间的常规 .animate 来制作动画,其中元素最终恢复到步骤 1 中的状态。

这是一个例子。

/* css file */
.animatedObject
{
    width:60%;
}

// javascript file
$('.animatedObject')
    .animate({width: '-=20%'}, 0)
    .animate({width: '+=20%'}, 1000);

至少对我来说,使用此代码有几个优点。首先,我很清楚我想要制作什么动画。其次,如果禁用了 javascript,则该对象将处于动画的结束状态,这通常是我希望它优雅降级的地方。第三,对象可以稍微改变位置以使用 css 进行调整,并且动画看起来仍然大致相同。

我不使用 .css 的原因是,如果我尝试使用 .css 方法将动画替换为 0 持续时间,我会得到不同的动画起点。我认为它不支持 += 或 -=,或者如果支持,它的行为会有所不同。

那么,这是一个很好的方法吗?什么是行业标准方式?

【问题讨论】:

  • 为什么你认为它的行为不同?
  • 因为我写了一些测试代码来尝试一下。

标签: javascript jquery html


【解决方案1】:

你仍然可以使用.css()

var anObj = $('.animatedObject');
anObj.css("width", anObj.css("width") - (20 / anObj.css("width"))).animate({
    width: '+=20%'
}, 1000);

我相信这会更快。

编辑:

我使用jsperf.com 为您做了一个小基准测试。这是我的结果(使用Google Chrome):

.animate({}, 0)

代码:

$('.animatedObject')
    .animate({width: '-=20%'}, 0)
    .animate({width: '+=20%'}, 1000);

最终结果:

10,013 operations per second
±7.48%
fastest

.css();

代码:

var anObj = $('.animatedObject');
anObj.css("width", anObj.css("width") - (20 / anObj.css("width"))).animate({
    width: '+=20%'
}, 1000);

最终结果:

2,477 operations per second
±6.39%
75% slower

结论

保留动画功能。事实证明,使用.css() 实际上更慢。我想这是你有2个额外功能的事实。这不值得。这对我来说实际上是一个惊喜,因为我认为.css() 会比它运行得更快。 Test this yourself 在您的浏览器中!

【讨论】:

  • 这可能会更快,但我的理智会受到打击。会快多少?我问这个问题的原因之一是要知道持续时间为 0 的 .animate 需要什么样的性能。如果与使用 .css 相比没有那么多,我想为了简单起见,我会继续使用 .animate。
猜你喜欢
  • 2018-11-12
  • 1970-01-01
  • 2018-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-15
  • 2012-09-11
  • 1970-01-01
相关资源
最近更新 更多