我是一个极端的新手,所以对一个公认的愚蠢问题道歉。但我已经研究并尝试了几种方法来使这个功能起作用,似乎无法得到它。我正在上网,我正在尝试构建一个简单的应用程序,其中图像在屏幕上移动,用户尝试单击它 - 当他们单击图像时,图像消失。我能够构造setInterval函数但无法使clearInterval函数起作用。
(对于公认的政治性质的代码道歉!只是一点美国的政治幽默。没有冒犯的意图!)
<h2>See if you can click on Hillary before she changes her position!</h2>
<p class="bold">This is your time:<span id="time">0</span>s</p>
<div id="box">
<img src="images/hillary.jpg" style="width:100%; height:100%">
</div>
<script type="text/javascript">
var time; var top; var left;
var makeBox;
function makeBox() {
time=Math.random();
time=1000*time;
setInterval(function () {
top=Math.random();
top=top*300;
left=Math.random();
left=left*1000;
document.getElementById("box").style.top=top+"px";
document.getElementById("box").style.left=left+"px";
document.getElementById("box").style.display="block";
createdTime=Date.now();
},time);
}
makeBox();
function myStopFunction() {
clearInterval(makeBox);
}
document.getElementById("box").onclick= function(){
clearInterval(makeBox);
this.style.display="none";
};
</script>
贾斯汀
答案 0 :(得分:1)
要清除计时器,您需要先存储它。使用setInterval
创建间隔时,应将其返回值存储在变量中。然后,当您拨打clearinterval
时,请将变量传入。
以下代码片段包含您需要的内容:
var myTimer;
function makeBox() {
time=Math.random();
time=1000*time;
myTimer = setInterval(function () {
top=Math.random();
top=top*300;
left=Math.random();
left=left*1000;
document.getElementById("box").style.top=top+"px";
document.getElementById("box").style.left=left+"px";
document.getElementById("box").style.display="block";
createdTime=Date.now();
},time);
}
makeBox();
function myStopFunction() {
clearInterval(myTimer);
}