jQuery Animation Speed?

杀马特。学长 韩版系。学妹 提交于 2019-11-29 01:26:51

For the updated question:
First, here's a working demo with the behavior you want. What we're doing here is adjusting the speed based on the amount needed to move, because speed isn't an accurate description, it's the duration, moving a shorter distance over the same duration means a slower move, so we need to scale the duration with the distance we need to move. For moving backwards, it looks like this:

var oldLeft = ul.offset().left;
ul.animate({left: 0}, -oldLeft * speed, 'linear');

Since the <ul> scrolls with a negative left position, we need to move the inverse of that many pixels to get back to the beginning, so we're using -oldLeft (it's current left position).

For the forward direction, a very similar approach:

var newLeft = divWidth - ulWidth,
    oldLeft = ul.offset().left;
ul.animate({left: newLeft + 'px'}, (-newLeft + oldLeft) * speed, 'linear');

This gets the new left property, the end being the width of the <ul> minus the width of the <div> it's in. Then we subtract (it's negative so add) that from the current left position (also negative, so reverse it).

This approach gives your speed variable a whole new meaning, it now means "milliseconds per pixel" rather than the duration it did before, which seems to be what you're after. The other optimization is using that cached <ul> selector you already had, making things a bit faster/cleaner overall.


For the original question:
Keep it simple, just half the time for half the distance, like this:

$(function() {
    $('#a').animate({left: '250px'}, 500, 'linear');
    $('#b').animate({left: '500px'}, 1000, 'linear');
});

You can try a demo here

I made a plugin that does exactly what you want. You can use Supremation to specify the speed of the animation as opposed to the duration.

linear only specifies that the animation should be done in linear increments and not speed up or slow down as it finishes. If you want the two animations to be the same speed, just double the time it takes for the animation that is twice the distance:

$('#a').animate({left: '250px'}, 1000, 'linear');
$('#b').animate({left: '500px'}, 2000, 'linear');
Reigel

something like this??

demo

$('#a,#b').animate({left: '250px'}, 1000, 'linear',
    function(){
       $('#b').animate({left: '500px'}, 1000, 'linear');   
    }
);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!