本文實例講述了JS實現光滑展開合攏的選單效果代碼。分享給大家供大家參考。具體如下:
這是一個光滑展開又合攏的JS選單效果,無jQuery插件,完全JavaScript程式碼實現,沒有過多修飾,有興趣的美化一下,肯定是款不錯的折疊選單。
運作效果截圖如下:
線上示範網址如下:
http://demo.jb51.net/js/2015/js-swift-fade-in-out-menu-style-codes/
具體程式碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3c.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="Content-Type" content="html/txt; charset=utf-8" /> <title>光滑展开合拢的JS菜单效果</title> <style> *{margin:0;padding:0;} ul,li{list-style:none;} #con{width:164px; margin:50px auto 0;} #con h4.top{ height:4px; width:164px; overflow:hidden;} #con h4.bottom{height:4px; width:164px;overflow:hidden;} #con div{height:0px; overflow:hidden;} #con h3{border-top:2px solid #fff; border-bottom:1px solid #D6EFFF;} </style> <script language="javascript"> var speed = 30; var oCon = null; var oH3List = null; var oDivList = null; var oUlList = null; var oldNum = null; var clickNum = null; var hideTimer=null; var showTimer=null; window.onload=function(){ oCon = document.getElementById("con"); oH3List = oCon.getElementsByTagName("h3"); oUlList = oCon.getElementsByTagName("ul"); oDivList = oCon.getElementsByTagName("div"); for(var i=0;i<oUlList.length;i++){ oH3List[i].xuhao=i; oH3List[i].onclick=function(){ clickNum =this.xuhao; changeCatalog(); }; } } function changeCatalog(){ var old_num_2,click_num_2; old_num_2 = null; click_num_2= null; if(oldNum==null){ click_Num_2=clickNum; showTimer = setInterval("showUl("+click_Num_2+")",speed); }else if(oldNum == clickNum){ old_num_2=oldNum; hideTimer = setInterval("hideUl("+old_num_2+")",speed); }else{ old_num_2=oldNum; click_num_2=clickNum; hideTimer = setInterval("hideUl("+old_num_2+")",speed); showTimer = setInterval("showUl("+click_num_2+")",speed); } } function showUl(num){ var move_num1 =Math.ceil((oUlList[num].offsetHeight-oDivList[num].offsetHeight)/10); if(move_num1>=1){ oDivList[num].style.height = oDivList[num].offsetHeight+move_num1+"px"; }else{ oldNum=num; clearInterval(showTimer); } } function hideUl(num){ var move_num2=Math.ceil((oDivList[num].offsetHeight)/10); if(move_num2>0){ oDivList[num].style.height=oDivList[num].offsetHeight -move_num2+"px"; }else{ clearInterval(hideTimer); if(clickNum==num){ oldNum=null; } } } </script> </head> <body> <div id="con"> <h4 class="top"></h4> <h1></h1> <h3>设计素材</h3> <div> <ul> <li>精品图标</li> <li>图片幻灯</li> <li>网页播放器</li> </ul> </div> <h3>模板素材</h3> <div> <ul> <li>企业网站</li> <li>儿童网站</li> <li>音乐网站</li> <li>Discuz模板</li> </ul> </div> <h3>脚本下载</h3> <div> <ul> <li>jQuery</li> <li>Ajax</li> <li>PHP</li> </ul> </div> <h3>网页特效</h3> <div> <ul> <li>菜单</li> <li>表单</li> <li>浏览器</li> </ul> </div> <h4 class="bottom"></h4> </div> </body> </html>
希望本文所述對大家的JavaScript程式設計有所幫助。