使用'jquery'的函数的奇怪行为

时间:2011-12-30 19:44:15

标签: jquery jquery-animate move

功能相对简单。单击该按钮时,对象将会掉落。如果再次按下按钮,对象将返回其随机位置并以相同的速度再次下降。 但每次我点击按钮,它(margin-top)变得更快。我不明白为什么?

HTML

<button id="fall" onclick="show_up()"> random-fall </button>
<div id="box" style="width:20px;height:20px;background:blue;">   </div>

脚本

var top;

function show_up() {
        top = 0;
        $("#box").css("margin-top", top);
        var rand = Math.random() * 500;
        rand = parseInt(rand);

        $("#box").css("margin-left", rand);

        fall_out();
    }

function fall_out() {
        top++;
        if (top < 500) {
            $("#box").css("margin-top", top);
            window.setTimeout('fall_out()', 10);
        }
        else {
            top = 0;
            fall_out();

        }
}

有人能告诉我解决问题的最佳方法吗?

3 个答案:

答案 0 :(得分:1)

应删除 else 分支中对 fall_out()的最后一次递归调用,并将margin-top设置为0.否则递归是无止境的。

答案 1 :(得分:1)

您的代码存在的问题是 fall_out()永远不会停止。它会继续自称。在阅读了评论@ Joop Eggen's answer后,似乎需要采取行动。

当您再次呼叫 show_up() 时,将再次调用fall_out(),这会导致第二次无限循环。这就是为什么你的对象会更快下降的原因,fall_out()将比第一次更频繁地调用(因为2个递归循环)。

您不能多次拨打fall_out()中的show_up()您可以例如设置一个这样的变量(started):

var top;
var started = false; // fall_out() has not been called yet

function show_up() {
        top = 0;
        $("#box").css("margin-top", top);
        var rand = Math.random() * 500;
        rand = parseInt(rand);

        $("#box").css("margin-left", rand);

        if(!started){
            started = true; //going to start the endless recursion function
            fall_out();
        }            
}

function fall_out() {
        top++;
        if (top < 500) {
            $("#box").css("margin-top", top);
            window.setTimeout(fall_out, 10); //note that it's not nice to call setTimeout with a string as argument
        }
        else {
            top = 0;
            fall_out();

        }
}

答案 2 :(得分:0)

你正在使用随机功能。这个脚本只是在x轴的随机位置移动框

相关问题