有一段html的小代碼,如下:function init(){ var planet=document.getElementById("greenplanet");
planet.innerHTML="RED ALERT: hit by phaser fire!"
setTimeout(planet.setAttribute("class","bluetext"),1000);
setTimeout(planet.setAttribute("class","redtext"),2000);然而,這樣執(zhí)行時(shí),會(huì)直接將Attribute變成redtext,沒有倒計(jì)時(shí)1000ms(我試過用5000ms,確實(shí)沒有倒計(jì)時(shí)),bluetext這一句也沒有執(zhí)行。我試著將代碼改成:function init2(){ var planet=document.getElementById("greenplanet");
planet.innerHTML="RED ALERT: hit by phaser fire!"; function a(){
planet.setAttribute("class","bluetext");
} function b(){
planet.setAttribute("class","redtext");
}
setTimeout(a,1000);
setTimeout(b,2000);
}就可以了。兩個(gè)setAttribute分別在倒計(jì)時(shí)后觸發(fā)。前后兩段代碼的區(qū)別,就是后一段將setAttribute代碼直接封裝到一個(gè)函數(shù)內(nèi)??墒莝etTimeOut的第一個(gè)參數(shù),不是既可以是函數(shù),也可以是代碼段碼?
JavaScript SetTimeout輸入?yún)?shù)的問題
胡說叔叔
2018-09-14 14:09:25