js--延时消失的菜单--(笔记)

html:有4个li,li下分别有一个span

<script>
   window.onload=function(){
    var aLi=document.getElementsByTagName('li'); 
    /*var timer=null; 全局timer的问题是:划到另一个项上,timer已被清除,上一项下拉菜单还遗留未收回,这样就是一个bug了;所以要每个li加一个timer,定义为自身的属性, 这样就只清除本身的timer ,不影响其他选项*/
    for(var i=0;i<aLi.length;i++){
      aLi[i].onmouseover=show;
      aLi[i].onmouseout=hide;
      aLi[i].getElementsByTagName('span')[0].onmouseover=show;
      aLi[i].getElementsByTagName('span')[0].onmouseout=hide; 
  }
function show(){ clearInterval(this.timer ); //划到另一项时,需要其他子项及时消失,so~ for(var i=0;i<aLi.length;i++){ //记得数组下标比其长度小1,但是i<(小于),所以无需减一 aLi[i].getElementsByTagName('span')[0].style.display='none'; } this.getElementsByTagName('span')[0].style.display='block'; } function hide(){ var _this=this;
   // 注:timer里面不能用this
this.timer=setTimeout(function(){ _this.getElementsByTagName('span')[0].style.display='none'; },1000); } } </script>
原文地址:https://www.cnblogs.com/alanaZ/p/4369305.html