一是报错offsetHeight,二是效果不是太好,鼠标移除太快会出问题……
代码见下图:
<!doctype html> <html> <head> <meta charset="utf-8" /> <style> body{ margin:0; padding:0; } a{ text-decoration: none; color:black; } nav{ height:40px; width:1200px; margin:0 auto; line-height:40px; background:#ddd; } nav ul{ margin:0; padding:0; height:40px; } nav ul li{ float:left; list-style:none; position:relative; } nav ul li a{ display:block; height:40px; line-height:40px; padding:0 90px; background:#eee; } nav ul li a:hover{ background:#aaa; color:white; } nav ul li ul li{ float:none; } nav ul li ul{ position:absolute; top:40px; left:0; display:none; height:0; overflow:hidden; } nav ul li:hover ul{ display:block; } nav ul li ul li a{ padding:0 50px; } nav ul li:hover ul li ul{ display:none; } nav ul li:hover ul li{ position:relative; } nav ul li:hover ul li:hover ul{ display:block; position: absolute; top:0; left:180px; } </style> <title>下拉菜单</title> </head> <body> <nav> <ul> <li><a href="">首页</a></li> <li><a href="">商城中心</a> <ul id="menu"> <li><a href="">javascript</a> <ul class="nav3"> <li><a href="">daohang1</a></li> <li><a href="">daohang2</a></li> <li><a href="">daohang3</a></li> </ul> </li> <li><a href="">jquery</a></li> <li><a href="">bootstrap</a></li> </ul> </li> <li><a href="">新闻中心</a></li> <li><a href="">关于我们</a> <ul> <li><a href="">javascript</a></li> <li><a href="">jquery</a></li> <li><a href="">bootstrap</a></li> </ul> </li> <li><a href="">联系我们</a></li> </ul> </nav> <script type="text/javascript"> window.onload=function(){ var lis=document.getElementsByTagName("li"); for (var i = 0; i < lis.length; i++) { lis[i].onmouseover=function(){ var u=this.getElementsByTagName("ul")[0]; if(u!=undefined){ u.style.display="block"; addH(u.id); } } lis[i].onmouseleave=function(){ var u=this.getElementsByTagName("ul")[0]; if (u!=undefined) { subH(u.id); }; } }; } function addH(id){ var ulList=document.getElementById(id); var h=ulList.offsetHeight; h+=1; if (h<=130) { ulList.style.height=h+"px"; clearTimeout("subH('"+id+"')",1); setTimeout("addH('"+id+"')",1); } else{ return; } } function subH(id){ var ulList=document.getElementById(id); var h=ulList.offsetHeight; h-=1; if (h>0) { ulList.style.height=h+"px"; clearTimeout("addH('"+id+"')",1); setTimeout("subH('"+id+"')",1); } else{ ulList.style.display="none;" return } } </script> </body> </html>