Bri*_*her 7 html javascript jquery
我已经习惯于通过执行以下操作来编写我的jquery动画.
使用css或javascript设置元素的初始状态(诸如宽度,高度,顶部,左边,不透明度等等).此初始状态是动画结束时的状态.
使用持续时间为0的.animate将元素移动到元素位于动画开头的状态.
使用具有适当持续时间的常规.animate来执行动画,最后,元素在步骤1中返回到状态.
这是一个例子.
/* css file */
.animatedObject
{
width:60%;
}
// javascript file
$('.animatedObject')
.animate({width: '-=20%'}, 0)
.animate({width: '+=20%'}, 1000);
Run Code Online (Sandbox Code Playgroud)
至少对我来说,使用此代码有几个优点.首先,我看起来很清楚我正在尝试制作动画.其次,如果禁用了javascript,则该对象将处于动画的结束状态,这通常是我希望它适用于优雅降级的地方.第三,对象可以使用css稍微改变位置以进行调整,并且动画看起来仍然大致相同.
我没有使用.css的原因是,如果我尝试使用.css方法替换0持续时间的动画,我会得到不同的动画起点.我不认为它支持+ =或 - =,或者如果它支持,它的行为有所不同.
那么,这是一个很好的方法吗?什么是行业标准方式?
好吧,你仍然可以使用.css()
:
var anObj = $(\'.animatedObject\');\nanObj.css("width", anObj.css("width") - (20 / anObj.css("width"))).animate({\n width: \'+=20%\'\n}, 1000);\n
Run Code Online (Sandbox Code Playgroud)\n\n我相信这样会见效更快。
\n\n我使用jsperf.com为您做了一些基准测试。这是我的结果(使用Google Chrome
):
.animate({}, 0)
$(\'.animatedObject\')\n .animate({width: \'-=20%\'}, 0)\n .animate({width: \'+=20%\'}, 1000);\n
Run Code Online (Sandbox Code Playgroud)\n\n10,013 operations per second
\n \xc2\xb17.48%
\nfastest
.css();
var anObj = $(\'.animatedObject\');\nanObj.css("width", anObj.css("width") - (20 / anObj.css("width"))).animate({\n width: \'+=20%\'\n}, 1000);\n
Run Code Online (Sandbox Code Playgroud)\n\n2,477 operations per second
\n \xc2\xb16.39%
\n75% slower
保留动画功能。事实证明使用.css()
实际上更慢。我猜这是因为你有两个额外的功能。这不值得。这实际上让我感到惊讶,因为我认为.css()
它的运行速度比它更快。在浏览器中亲自测试一下!