話不多說,代碼上來,有些知識點直接就在註釋里 HTML CSS JavaScript ...
話不多說,代碼上來,有些知識點直接就在註釋里
HTML
<div class="list-down"> <button id="btn">選擇項</button> <ul id="list-chooses" style="display: none;"> <li><a href="#">Python</a></li> <li><a href="#">JavaScript</a></li> <li><a href="#">Java</a></li> <li><a href="#">PHP</a></li> <li><a href="#">C++</a></li> <li><a href="#">C語言</a></li> <li><a href="#">Android</a></li> <li><a href="#">微信小程式</a></li> <li><a href="#">Node.js</a></li> <li><a href="#">Bootstrap</a></li> <li><a href="#">HTML && CSS</a></li> <li id="close"><a href="#">關閉</a></li> </ul> </div>
CSS
<style type="text/css"> * { margin: 0; padding: 0; font-size: 16px; /* 消除按鈕點擊之後預設出現的藍色邊框 */ outline: none; } ul { list-style: none; } .list-down { width: 150px; margin: 10px auto; text-align: center; } .list-down button { width: 150px; height: 40px; cursor: pointer; background-color: #ea6f5a; border: none; color: #ccc; } .list-down button:hover { color: #fff; font-size: 17px; font-style: 2000; } .list-down button:focus { border: none; } .list-down #list-chooses { border-top: 1px solid #ddd; } .list-down #list-chooses li { width: 150px; height: 0; line-height: 40px; background-color: #ea6f5a; } .list-down #list-chooses li a { color: #ccc; text-decoration: none; } .list-down #list-chooses li:hover a { color: #fff; font-size: 17px; font-style: 2000; } .list-down #list-chooses li#close { border-top: 1px solid #ddd; } </style>
JavaScript
<script type="text/javascript"> window.onload = () => { const listBtn = document.getElementById('btn') const lists = document.getElementById('list-chooses'); const listsLis = lists.querySelectorAll('li'); const listsCloseBtn = document.getElementById('close'); // 列表選項從上而下出現 let listDown = () => { let startHeight = 0; let stopHeight = 40; let timeId = setInterval(() => { startHeight++; // 註意:forEach() 方法在 IE8 以下不支持 listsLis.forEach((item) => { item.style.height = startHeight + 'px'; }); if (startHeight >= stopHeight) { clearInterval(timeId); } }, 10); lists.style.display = 'block'; }; // 列表選項從下而上消失 let listUp = () => { let startHeight = 40; let stopHeight = 0; let timeId = setInterval(() => { startHeight--; listsLis.forEach((item) => { item.style.height = startHeight + 'px'; }); if (startHeight <= stopHeight) { clearInterval(timeId); } }, 10); // 這裡,如果不延時的話,會直接消失,而沒有上拉的效果 setTimeout(() => { lists.style.display = 'none'; }, 350); }; // 如果列表選項為隱藏,點擊則顯示;如果列表選項為顯示,點擊則隱藏 listBtn.addEventListener('click', () => { if (lists.style.display == 'none') { listDown(); } else { listUp(); } }); listsCloseBtn.addEventListener('click', () => { listUp(); }); }; </script>