jQuery动画运行缓慢 [英] jquery animate running laggy

查看:110
本文介绍了jQuery动画运行缓慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个闪烁的箭头.但是,当我在不同的浏览器中执行此脚本时,它的行为会很差. IE表示内存不足,Chrome会滞后一秒钟,然后表现良好,在Firefox中动画会发粘.

I am trying to create a flashing arrow. However when I execute this script in different browsers it behaves badly. IE says its out of memory, Chrome lags for a second and then behaves well and in firefox the animation is sticky.

希望有人可以找到一种方法,使我可以平滑地为闪烁的箭头设置动画.谢谢

Hope someone can work out a way that I can animate a flashing arrow smoothly. Thanks

aniPointer($('#arrow'));

function aniPointer(point) {
        point.animate({opacity: 1.0}, {duration: 300})
            .animate({opacity: 0.2}, {duration: 700})
            .animate({opacity: 0.2}, {duration: 300})
            .animate({opacity: 1.0}, {duration: 300, complete: aniPointer(point)})
    }

推荐答案

您正在创建一个无限循环.您是故意这样做的,但是它的运行速度比您想象的要快得多. complete具有功能参考.通过将括号添加到回调函数的名称中,您可以立即调用aniPointer并将返回值传递给complete,而不是传递对aniPointer本身的引用以在以后的某个时间触发.

You're creating an infinite loop. You did so intentionally, but its running a lot faster than you think. complete takes a function reference. By adding the parens to the name of the callback function you are invoking aniPointer immediately and passing the return value to complete instead of passing a reference to aniPointer itself to be fired at some later time.

即使如此,该序列真的是您想要执行的操作吗?

Even so, is that sequence really what you want to do?

您正在做

go to 1.0 over 300ms
go to 0.2 over 700ms
go to 0.2 over 300ms
go to 1.0 over 300ms
repeat

假设您从1.0开始,这实际上是:

Assuming you're starting at 1.0 this is actually:

wait 300ms
go to 0.2 over 700ms
wait 300ms
go to 1.0 over 300ms
repeat

如果您正在寻找稳定的脉搏,可以执行以下操作:

If you're looking for a steady pulse you could do something like this:

function pulse($elem) {
    return window.setInterval(function() {
        $elem.animate({opacity: 0.2}, 700)
             .animate({opacity: 1.0}, 300);
    }, 1000);
}

或者,如果您有意暂停,则可以执行以下操作:

Or if you were pausing intentionally you could do:

function pulse($elem) {
    return window.setInterval(function() {
        $elem.animate({opacity: 0.2}, 700);
        window.setTimeout( function() {
            $elem.animate({opacity: 1.0}, 300);
        }, 1000);
    }, 1600);
}

如果愿意,返回值将允许您停止动画:

The return value would allow you to stop the animation if you wanted to like so:

var pulseIntervalId = pulse( $('#arrow_id') );

//some time later...
window.clearInterval(pulseIntervalId);

任何一种版本都可以解决无限循环问题,从而允许回调函数在不被过早调用的情况下具有对pulsing元素的引用.

Either version would skirt the infinite loop issue, allowing the callback to have the reference to the pulsing element without being invoked prematurely.

这篇关于jQuery动画运行缓慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆