為什么我將oSubNav.time 改成一個普通變量 timer就不行了
indow.onload=function(){
? ? var aLi=document.getElementsByTagName('li');
? ? for(var i=0; i<aLi.length; i++){
? ? ? ?aLi[i].onmouseover=function(){
? ? ? ? ? ? var oSubNav=this.getElementsByTagName('ul')[0];
? ? ? ? ? ? if(oSubNav){
? ? ? ? ? ? clearInterval(timer);
? ? ? ? ? ? var timer=setInterval(function(){
? ? ? ? ? ? ? ? ? ? oSubNav.style.height=oSubNav.offsetHeight+16+"px";
? ? ? ? ? ? ? ? ? ? if(oSubNav.offsetHeight>=120)
? ? ? ? ? ? ? ? ? ? clearInterval(timer);
? ? ? ? ? ? ? ? },30)
? ? ? ? ? ? ?}
? ? ? ? ? }
? ? ? ? //鼠標(biāo)離開菜單,二級菜單動畫收縮起來。 ? ? ? ?
? ? ?aLi[i].onmouseout=function(){
? ? ? ? ? ? var oSubNav=this.getElementsByTagName('ul')[0];
? ? ? ? ? ? if(oSubNav){
? ? ? ? ? ? clearInterval(timer);
? ? ? ? ? ? var timer=setInterval(function(){
? ? ? ? ? ? ? ? ? ? oSubNav.style.height=oSubNav.offsetHeight-16+"px";
? ? ? ? ? ? ? ? ? ? if(oSubNav.offsetHeight<=0)
? ? ? ? ? ? ? ? ? ? clearInterval(timer);
? ? ? ? ? ? ? ? },30)
? ? ? ? ? ? ?}
? ? ? ? ? }
? ? ? ??
? ? }
}
程序就出BUG了,鼠標(biāo)滑到li標(biāo)簽,窗口也會彈回,一定要建立對象的屬性來保存setInterval的返回值嗎
2016-04-26
oSubNav就是this.getElementsByTagName('ul')[0],oSubNav是遍歷所有l(wèi)i,如果當(dāng)前li下有ul,即當(dāng)前的li是一級菜單,才繼續(xù)執(zhí)行后面的邏輯。為什么要把后面的計時器綁在this上呢?因為每個this也就是每個一級菜單有著一個共同的計時器。假設(shè)你迅速的進入、移出,再移入某個一級菜單,因為使用同一個定時器,移出時會清空移入的定時器,移入時清空移出的定時器,二級菜單不會卡殼。如果改成一個普通的變量timer,timer的作用域僅限于該次函數(shù)內(nèi)部調(diào)用,移入和移出使用了不同的計時器,二級菜單的高度會不斷的+12px和-12px,每次移入都產(chǎn)生了新的一個timer?;蛘吣阆雱?chuàng)建一個全局的timer所有一級菜單共用,一級菜單同樣會卡殼,不能單獨的縮回。這樣每個一級菜單共用的一個變量,把它放在this的屬性上再方便不過了。