萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

網頁下拉選單原理與實作完整教學(CSS+JS)

模擬 Windows 風格下拉選單,核心原理:CSS 定位 + display 顯隱 + JS 事件切換。本文從基礎原理、關鍵屬性、完整範例、美化進階層層遞進。

核心 CSS 屬性

  • 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 切換樣式

滑鼠懸停時切換 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 定位子選單。
  • 現代專案建議改用純 CSS :hover + > 選擇器,或 <details>/<summary> 原生互動元素,減少 JS 依賴。
copyright © 萬盛學電腦網 all rights reserved