jQuery animate() 参数的确切规则是什么?
jQuery 1.4.2 的 animate() API 规范 是,
.animate( properties, [ duration ], [ easing ], [ callback ] )
但似乎我们可以提供 duration
、callback
和 no easing
.animate({left: '+= 100'}, 600, doThis)
就可以了。
但是,如果我们提供easing
和callback
以及noduration
,
.animate({left: '+=100'}, 'swing', doThis)
那么缓动将不会生效。那么 API 到底应该是什么?
更新:请参阅下面我的回答。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通常 jQuery 按类型确定可选参数,例如,这是可行的:
但在持续时间/缓动的情况下,因为它们都是字符串,所以不能(如果有单个字符串,则 它假设它是持续时间)。您需要使用
'normal'
作为持续时间来调用它,如下所示:或者使用
.animate(options,properties)
版本,如下所示:Normally jQuery determines optional parameters by types, e.g. this works:
But in the case of duration/easing, since they're both strings it can't (and if there's a single string, it assumes it's the duration). You need to either call it with
'normal'
as the duration, like this:Or use the
.animate(options, properties)
version, like this:尽管我对 API 规范仍然不太确定,但这些是一些可行的解决方案:
1) 提供
400, "swing", doThis
,因为 400 似乎是默认持续时间(查找>fast:
在 jquery 代码中,你可以看到 fast 是 600,slow 是 200(如规范中所示),_default 是 400。2) 提供
undefined, "swing", doThis
和有用。提供null, "swing", doThis
并且它也可以工作。尽管如果没有以这种方式记录的话,依赖这种方法可能并不好。如果省略参数,undefined
才是真正的方法,但有时人们说使用null
,即使它不是正式正确的。3)只需使用
{easing: "swing"}
这是跳过持续时间并提供缓动方法的官方方法。如果需要回调,则使用{easing: "swing",complete: doThis}
解决方案 3 似乎是最好的,因为它没有使用规范中模糊的部分,并且完全符合规范中更清晰的部分。
even though I am still not so sure about the API spec, these are some viable solutions:
1) supply
400, "swing", doThis
, since 400 seems to be the default duration (look forfast:
in the jquery code and you can see fast is 600, slow is 200 as in the spec, and _default is 400.2) supply
undefined, "swing", doThis
and it works. Supplynull, "swing", doThis
and it works too. Although maybe it is not good to depend on this method if it is not documented this way.undefined
is the really way to go if argument is omitted but sometimes people say usenull
even though it is not officially correct.3) just use
{easing: "swing"}
and that's the official way to skip the duration and provide a easing method. if callback is needed, then use{easing: "swing", complete: doThis}
Solution 3 seems to be the best, as it doesn't use what the vague part of the spec and go totally with the clearer part of the spec.