使用';jquery';

使用';jquery';,jquery,jquery-animate,move,Jquery,Jquery Animate,Move,功能相对简单。单击该按钮时,对象将掉落。如果再次按下按钮,对象将返回其随机位置,并以相同的速度再次下落。 但每次我点击这个按钮,它(页边距顶部)就会变得更快。我不明白为什么 HTML 随机下降 剧本 var-top; 函数show_up(){ top=0; $(“#框”).css(“页边空白顶部”,顶部); var rand=Math.random()*500; rand=parseInt(rand); $(“#框”).css(“左边距”,兰德); 掉出来; } 函数fall_out(){ t

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

HTML

随机下降
剧本

var-top;
函数show_up(){
top=0;
$(“#框”).css(“页边空白顶部”,顶部);
var rand=Math.random()*500;
rand=parseInt(rand);
$(“#框”).css(“左边距”,兰德);
掉出来;
}
函数fall_out(){
top++;
如果(顶部<500){
$(“#框”).css(“页边空白顶部”,顶部);
setTimeout('fall_out()',10);
}
否则{
top=0;
掉出来;
}
}

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

应该删除else分支中对fall\u out()的最后一个递归调用,并将margin top设置为0。否则递归是无止境的。

您使用的是随机函数。此脚本只是在x轴上随机移动长方体

代码的问题是,
fall\u out()
永远不会停止。它会继续自我召唤。在读了你的评论后,@这似乎是你想要的行为

第二次调用
show\u up()
时,将再次调用
fall\u out()
,这将导致第二个无限循环。这就是为什么对象下降得更快的原因,
fall\u out()
将比第一次更频繁地被调用(因为有两个递归循环)

您不能在
show\u up()
中多次调用
fall\u out()
例如,您可以这样设置一个变量(
已启动
):

var-top;
var start=false;//尚未调用fall_out()
函数show_up(){
top=0;
$(“#框”).css(“页边空白顶部”,顶部);
var rand=Math.random()*500;
rand=parseInt(rand);
$(“#框”).css(“左边距”,兰德);
如果(!已启动){
started=true;//将启动无穷递归函数
掉出来;
}            
}
函数fall_out(){
top++;
如果(顶部<500){
$(“#框”).css(“页边空白顶部”,顶部);
setTimeout(fall_out,10);//注意,用字符串作为参数调用setTimeout并不好
}
否则{
top=0;
掉出来;
}
}

不是在无限循环中掉出来的吗?不管top的值是多少,您都将继续调用
fall\u out
。请注意:您不应将字符串传递给
setTimeout
(它使用
eval
)。你应该传递函数<代码>设置超时(下降,10)这只是开始。也就是说,如果盒子下降500px,它会自动再次调用函数,开始下降。太棒了!它工作得很好。。我还有一个疑问。我也可以用for循环而不是if来编写这个函数。如果是,那么我如何才能放慢速度,看到每一步?
<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();

        }
}
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();

        }
}