gpt4 book ai didi

jQuery : stop recursivity with event

转载 作者:行者123 更新时间:2023-12-01 05:57:46 24 4
gpt4 key购买 nike

我正在递归地制作 3 个点的动画。我想在单击#myElement 后停止递归。

这是我的代码:

    $(document).ready(function(){       
var positions = {
'pos1': {"X": $('#point_1').css('left'), "Y": $('#point_1').css('top')},
'pos2': {"X": $('#point_2').css('left'), "Y": $('#point_2').css('top')},
'pos3': {"X": $('#point_3').css('left'), "Y": $('#point_3').css('top')},
};

animate3Points(positions);
});

function animate3Points(p) {
animatePoints('#point_3', p, p.pos1);
animatePoints('#point_2', p, p.pos2);
animatePoints('#point_1', p, p.pos3);
}

function animatePoints(selector, p, pos) {
$(selector).animate({
'left': pos.X ,
'top': pos.Y
}, 2000, 'easeInOutQuad', function() {

// while #myElement has not been clicked,
// call again animate3points for recursivity :

if (selector == '#point_1') { // just to be recalled one time
p2 = changePosition(p);
animate3Points(p2);
}

// end while

});
}

function changePosition(obj) {
firstEl = obj.pos1;
obj.pos1 = obj.pos2;
obj.pos2 = obj.pos3;
obj.pos3 = firstEl;

return obj;
}

动画可以工作,但可能需要以另一种方式实现来停止递归。

一个想法?

最佳答案

您应该使用在函数外部实例化的全局变量,并将其用作递归调用何时停止的逻辑条件。例如:

var keepAnimating = true;

function animate3Points(p) {
if(keepAnimating) {
animatePoints('#point_3', p, p.pos1);
animatePoints('#point_2', p, p.pos2);
animatePoints('#point_1', p, p.pos3);
}
}

在您的点击事件中,您需要设置 keepAnimating = false;。这将停止递归,但您可能还需要停止动画。

但是,无限递归是一个非常糟糕的主意。您将导致浏览器使用大量内存。您应该优化代码以使用循环而不是递归。

关于jQuery : stop recursivity with event,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13726682/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com