[英]Randomize a div position
我編寫了一個程序,您可以按一下按鈕,然后div會隨機定位自己。
function Init()
{
div = document.getElementById("pixel");
spaceW = screen.height - div.height;
spaceH = screen.width - div.width;
setInterval(moveIt, 1000);
}
function moveIt()
{
div.style.top = (100*Math.random()) + "%";
div.style.left = (100*Math.random()) + "%";
}
問題是,僅當我使用setInterval
時,它才有效。 我只希望div移動一次。 我將擦除setInterval
,然后呢?
如果您仔細閱讀文檔,將會看到setInterval()在特定的固定間隔觸發。 如果只想一次觸發函數,請使用setTimeout()代替:
function Init() { div = document.getElementById("pixel"); spaceW = screen.height - div.height; spaceH = screen.width - div.width; setTimeout(moveIt, 1000); } function moveIt() { div.style.top = (100*Math.random()) + "%"; div.style.left = (100*Math.random()) + "%"; } Init();
#pixel { width: 50px; height: 50px; background-color: red; position: absolute; }
<div id="pixel"></div>
SetInterval在每個給定間隔重復
setTimeout在超時到期時運行一次
聽起來好像您需要使用setTimeout才能運行一次
function sayHi() {
alert('Hello');
}
setTimeout(sayHi, 1000)
看到不是我創造的小提琴
如果以這種方式工作,則為setInterval()聲明一個變量,則可以在其他函數中破壞該間隔,例如varible.clearInterval()
some=setInterval(moveIt,200);//this one in caller function.
some.clearInteraval();//here this statment should be in moveIt
在這里你應該聲明一些全局變量
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.