<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style> body,ul,li,.sfq,h3{ margin: 0; padding: 0; list-style: none; } h3{ height: 30px; width: 200px; background-color: #00cdc5; text-align: center; line-height: 30px; color: #fff; } li{ height: 30px; width: 200px; background-color: rgba(158, 123, 255, 0.26); color: #fff; } ul{ overflow: hidden; } </style> </head> <body> <div id="hello"> <h3 >我在第一樓</h3> <ul> <li>good luck </li> <li>hello javascript</li> <li>hello programmer</li> </ul> <h3>我在第二樓</h3> <ul> <li>good luck </li> <li>hello javascript</li> <li>hello programmer</li> </ul> <h3 >我在第三樓</h3> <ul> <li>good luck </li> <li>hello javascript</li> <li>hello programmer</li> </ul> </div> <script type="text/javascript"> function $(id) { return document.getElementById(id); } var temph3 = $('hello').getElementsByTagName('h3'); //獲得h3的節點對象 for(var i=0;i<temph3.length;i++) { temph3[i].onclick=function(){ var tempnext= this.nextElementSibling;//h3下一個兄弟元素節點ul,避免指向空節點; if(tempnext.style.display!='none'){ //若是ul沒有被關閉則執行代碼 var offsethight=tempnext.offsetHeight; //設置當前ul的可見高度 var setintervalid = setInterval( function(){ offsethight=tempnext.offsetHeight; tempnext.style.height=offsethight-10+'px';//★逐漸關閉的時候,ul必定要overflow: hidden; if(offsethight<10){ //當高度小於10時改變display的值爲none,並關閉時間間隔; tempnext.style.display='none'; clearInterval(setintervalid); } },50 ) }else //若是ul處於關閉狀態則執行代碼 { tempnext.style.display='block';//首先設置display爲可見狀態 var offsethight=tempnext.offsetHeight; var setintvalid=setInterval(function(){ offsethight=tempnext.offsetHeight; tempnext.style.height=offsethight+10+'px';//高度加10 if(offsethight>=90){ tempnext.style.height=offsethight+'px';// ★讓最後中止的ul高度等於可見的高度,避免了出現空白的現象; clearInterval(setintvalid); } },50) } } } </script> </body> </html>