在jquery中使用.animate自动触发函数

时间:2014-02-18 07:25:44

标签: jquery

我正在进行一个jQuery项目并且在某个时候陷入困境 我正在使用jQuery .animate(),即:$(".planeid").animate({top:'590px'},1000); 最初的最高值为0

top属性值达到200时,可以触发任务吗? 提前致谢

2 个答案:

答案 0 :(得分:1)

是的,你可以通过使用step回调动画功能来实现这一点。

$(".planeid").animate({top:'590px'},
                      { 
                       duration : 1000 , 
                       step : function(currentValue){
                           if(currentValue === 200)
                            {
                              //your code here.
                            }
                       }});

答案 1 :(得分:1)

我建议,因为不能保证动画值在给动画时精确等于给定值,检查动画值/属性是否超过检查点而不是等于它:

$(".planeid").animate({
    top: '590px'
}, {
    duration: 1000,
    step: function () {
        // caching the relevant node, since we're using it a lot:
        var _t = this;
        // using parseInt() here, but parseFloat could be used instead:
        if (parseInt(_t.style.top, 10) > parseInt(_t.getAttribute('data-observe'), 10)) {
            console.log('passed ' + _t.getAttribute('data-observe') + ' (' + _t.style.top + ')');
            // removing the attribute in order to allow the code to be executed only
            // once per animation (rather than constantly once it's animated beyond
            // the given point
            _t.removeAttribute('data-observe');
        }
    }
});

JS Fiddle demo

以上内容只会运行一次(因为data-observe属性在第一次与if条件匹配时被删除;然而,我建议多次运行:

// using prop() to set the flag to keep observing (on subsequent animations):
$(".planeid").prop('keepObserving', true).animate({
    top: '590px'
}, {
    duration: 1000,
    step: function () {
        var _t = this;
        if (parseInt(_t.style.top, 10) > parseInt(_t.getAttribute('data-observe'), 10) && _t.keepObserving) {
            console.log('passed ' + _t.getAttribute('data-observe') + ' (' + _t.style.top + ')');
            // setting the flag to false, so it runs only once per animation
            // not on every increment after passing the given point:
            _t.keepObserving = false;
        }
    },
    complete: function(){
        // once the animation is complete we reset the flag so it will
        // all re-run on every subsequent animation:
        this.keepObserving = true;
    }
});

JS Fiddle demo

参考文献: