如何按比例设置 jQuery 动画的持续时间?
我创建了一个快速测试来展示我想要做什么:
http://jsfiddle.net/zY3HH/< /a>
如果单击“切换宽度”按钮一次,正方形将需要一秒钟才能增长到全宽。再次单击它,需要一秒钟才能缩小到零宽度。
但是,快速连续单击“切换宽度”按钮两次 - 第二次当正方形仅增长到其总宽度的一小部分(例如 10%)时 - 您会注意到动画仍然需要一整秒的时间才能完成将正方形返回到零宽度,这看起来很尴尬,IMO。
虽然这种行为是预期的,但我希望后一个动画发生的时间与其覆盖的宽度成正比。换句话说,如果当正方形达到其总宽度的 10% 时再次单击“切换宽度”,我希望它需要大约 1/10 秒才能缩小到零宽度。
(我认为)使 duration
属性的值动态化(在 jQuery click
处理程序运行时计算)以测量正方形的当前宽度应该相对容易并相应地确定持续时间。
但是,我是否缺少更好的方法来做到这一点? jQuery 是否提供了一种简单的方法,或者公开了某种方法或属性来使这变得更容易?
I've created a quick test to show what I'm trying to do:
If you click the "Toggle Width" button once, a square will take one second to grow to full width. Click it again, and it will take one second to shrink down to zero width.
However, click the "Toggle Width" button twice in rapid succession - the second time when the square has grown to only a small fraction of its total width (like 10%) - you'll notice that the animation still takes a full second to return the square to zero width, which looks awkward, IMO.
While that behavior is expected, I'd like the latter animation to happen in an amount of time that's proportional to the width that it's covering. In other words, if you click "Toggle Width" a second time when the square is at 10% of its total width, I'd like it to take about 1/10th of a second to shrink back to zero width.
It should be relatively easy (I think) to make the value of the duration
property dynamic, calculated when the jQuery click
handler is run, to measure the current width of the square and determine the duration accordingly.
However, am I missing a better way to do this? Does jQuery provide an easy way, or expose some sort of method or property to make this easier?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为 jQuery 没有任何内置实用程序可以执行此操作。然而,做你想做的事情所需的数学相当简单,所以我建议就走这条路。类似于:
这是一个工作示例: http://jsfiddle.net/zY3HH/2/
如果您您有一些空闲时间,也许您可以使持续时间插值逻辑更加通用,并将其打包为 jQuery 扩展/插件。
I don't think jQuery has any built-in utility for doing this. The math required to do what you want is fairly straightforward, however, so I'd suggest just going that route. Something like:
Here's a working example: http://jsfiddle.net/zY3HH/2/
If you've got some free time on your hands, maybe you could make the duration interpolation logic a bit more generic and package it up as a jQuery extension/plugin.
这就是你想要的 - http://jsfiddle.net/FloydPink/qe3Yz/
This is what you want - http://jsfiddle.net/FloydPink/qe3Yz/