我正在进行一个jQuery项目并且在某个时候陷入困境
我正在使用jQuery .animate()
,即:$(".planeid").animate({top:'590px'},1000);
最初的最高值为0
。
当top
属性值达到200
时,可以触发任务吗?
提前致谢
答案 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');
}
}
});
以上内容只会运行一次(因为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;
}
});
参考文献: