模擬 Windows 風格下拉選單,核心原理:CSS 定位 + display 顯隱 + JS 事件切換。本文從基礎原理、關鍵屬性、完整範例、美化進階層層遞進。
position: absolute/relative 定位選單面板。left/top 精準對齊觸發按鈕。display: none/block 控制顯隱。<style>
td,div { font: normal 12px 宋體; }
#menu01 { position:absolute; display:none; width:120px; background:#fff; border:1px solid #ccc; }
</style>
<table><tr>
<td onmouseover="menuShow(menu01)" onmouseout="menuHide(menu01)">選單按鈕</td>
</tr></table>
<div id="menu01" onmouseout="menuHide(this)">
選單項目1<br>選單項目2<br>選單項目3
</div>
<script>
function menuShow(m) { m.style.display='block'; }
function menuHide(m) { m.style.display='none'; }
</script>
滑鼠懸停時切換 className,一次改變多個 CSS 屬性(背景、邊框、游標),比逐一設 style.xxx 更易維護:
.style_normal { color: gray; }
.style_over { color: red; background: #ffffcc; border: 1px solid red; cursor: pointer; }
<span class="style_normal"
onmouseover="this.className='style_over'"
onmouseout="this.className='style_normal'">
滑鼠移上變紅
</span>
<ul><li> 語意化結構。<ul> + position:absolute 定位子選單。:hover + > 選擇器,或 <details>/<summary> 原生互動元素,減少 JS 依賴。