Javascript 在函数满足要求后停止函数

Javascript 在函数满足要求后停止函数,javascript,html,dom,settimeout,onload,Javascript,Html,Dom,Settimeout,Onload,这是我能描述它的最好方式。基本上,我有一个jpg,我在屏幕上滚动加载。我应该能够停止图像,并使其隐藏后,它已通过3下降通过屏幕。我已经做了几个小时了,但是不知道如何在不使用onClick按钮的情况下让它工作。我需要它自己停下来。以下是脚本: function moveit() { dom=document.getElementById("roman").style; dom.top= parseInt(dom.top)+tinc+"px"; dom.

这是我能描述它的最好方式。基本上,我有一个jpg,我在屏幕上滚动加载。我应该能够停止图像,并使其隐藏后,它已通过3下降通过屏幕。我已经做了几个小时了,但是不知道如何在不使用onClick按钮的情况下让它工作。我需要它自己停下来。以下是脚本:

    function moveit()
    {
    dom=document.getElementById("roman").style;


    dom.top= parseInt(dom.top)+tinc+"px"; 
    dom.left= startleft+"px";


    dom.visibility= "visible";
    startleft=startleft+linc;

    if (startleft<= 20)     
    {linc=linc*-1;      
    window.document.roman.src="roman.jpg"; }

    if (startleft>= window.screen.width-10) 
    {linc=linc*-1;
    window.document.roman.src="roman.jpg"; }


    to=setTimeout("moveit();", 100) ;
    }
函数moveit()
{
dom=document.getElementById(“罗马”).style;
dom.top=parseInt(dom.top)+tinc+“px”;
dom.left=startedeft+“px”;
dom.visibility=“visible”;
STARTEFT=STARTEFT+linc;
if(startedeft=window.screen.width-10)
{linc=linc*-1;
window.document.roman.src=“roman.jpg”;}
to=setTimeout(“moveit();”,100);
}
身体是这样的:

    <body onload="moveit()">
    <div id="roman" style="position:absolute; top: 0px; left: 0px; visibility: hidden;">
    <img name="roman" src="roman.jpg"/>
    </div>

    <form>
    <div id="button" style="position:absolute; top: 315px; left: 10px;">
    <input type="button" value="stop" onClick="clearTimeout(to)">
    </div>
    </form>


我尝试了几种方法,但未能删除按钮方面。我想让图像从右到左进行3次完整传递,停止,然后隐藏。有什么想法吗?没有按钮怎么办?

您想使用计数器变量来跟踪图像水平反弹的次数。一旦计数器达到某个数字,不要重置超时:

var passes = 0;

var imageStyle = document.getElementById("roman").style;
imageStyle.visibility = "visible"; 

// Referring to the image with document.roman isn't recommended; give it an ID
// and use getElementById instead.
window.document.roman.src = "roman.jpg";

function moveit() {
    imageStyle.top = parseInt(dom.top) + tinc + "px"; 
    imageStyle.left = startleft + "px";

    startleft = startleft + linc;

    if (startleft <= 20 || startleft >= window.screen.width - 10) {
        linc = linc * -1;
        passes++;
    }

    if (passes < 3) {
        to = setTimeout(moveit, 100);
    }
}
var passes=0;
var imageStyle=document.getElementById(“罗马”).style;
imageStyle.visibility=“可见”;
//使用document.roman引用图像是不推荐的;给它一个身份证
//并改用getElementById。
window.document.roman.src=“roman.jpg”;
函数moveit(){
imageStyle.top=parseInt(dom.top)+tinc+“px”;
imageStyle.left=startleft+“px”;
STARTEFT=STARTEFT+linc;
如果(startedeft=window.screen.width-10){
linc=linc*-1;
通过++;
}
如果(通过<3){
to=设置超时(moveit,100);
}
}

请注意,我删除了一些冗余代码。您不必每次启动计时器时都设置可见性或图像源。只需从头开始。

setTimeout中的字符串除了稍微降低代码的速度外,没有其他作用<代码>设置超时(“moveit();”,100)应该是
setTimeout(moveit,100)。谢谢,我把那个部分删掉了:)我的老师写了上面的原始代码,哈哈,我不认为它可能是对的。我很失望,我一直在花钱让他教我,因为他的代码在作业中使用时很少起作用>。谢谢你做了这些更改,我真的很感激:)我还需要将图像保留在身体中吗?或者我可以删除代码的相应主体部分吗?