彈跳視窗(Lightbox)是網頁上最基礎也最高頻的互動元件之一:點一下觸發連結,畫面浮現半透明遮罩與置中的內容框,再點關閉即可回到原頁面。它的原理其實非常單純——兩個疊在一起的 div,加上 z-index 分層,再用 JS 切換 display。
以下是一份可直接存成 HTML 檔執行的完整範例:
<html> <head> <meta charset="utf-8" /> <title>LIGHTBOX EXAMPLE</title> <style> .black_overlay{ display: none; position: absolute; top: 0%; left: 0%; width: 100%; height: 100%; background-color: black; z-index:1001; -moz-opacity: 0.6; opacity:.60; filter: alpha(opacity=60); } .white_content { display: none; position: absolute; top: 25%; left: 25%; width: 50%; height: 50%; padding: 16px; border: 16px solid orange; background-color: white; z-index:1002; overflow: auto; } </style> <script> function one(){ document.getElementById('light').style.display='block'; document.getElementById('fade').style.display='block' } function two(){ document.getElementById('light').style.display='none'; document.getElementById('fade').style.display='none' } </script> </head> <body> <p>可以根據自己要求修改css樣式 <a href="javascript:void(0)" onclick="one()">點擊這裡打開窗口</a> </p> <div id="light" class="white_content"> This is the lightbox content. <a href="javascript:void(0)" onclick="two()">Close</a> </div> <div id="fade" class="black_overlay"> </div> </body> </html>
層級分工。遮罩層 .black_overlay 的 z-index 是 1001,內容層 .white_content 是 1002,數字大的蓋在上面,這是唯一必須分清的順序關係。
透明度寫三遍是為了相容。opacity 是標準寫法,-moz-opacity 對應舊版 Firefox,filter: alpha(opacity=60) 則是 IE 的私有屬性。以今天的瀏覽器水準來說,只留 opacity 就足夠了。
定位方式。遮罩用 top/left: 0 配 width/height: 100% 鋪滿整個視窗;內容框用 top/left: 25% 加 width/height: 50% 讓它落在畫面中央區域,再用 padding 與粗邊框撐出視覺層次。overflow: auto 讓內容過長時可以自己捲動。
為什麼用 href="javascript:void(0)"。它讓連結保持可點擊的手型游標與鍵盤可聚焦性,但不會真的跳轉或把 # 塞進網址列。若想更嚴謹,可改用 <button> 並在事件處理器內呼叫 preventDefault()。
這個範例追求的是最小可行實作,若要投入正式專案,建議補上幾件事:把 position: absolute 改為 fixed,讓遮罩在頁面捲動時 tetap 釘在視窗上;加入 body 的 overflow 鎖定避免背景滾動;補上 ESC 鍵關閉與焦點管理,讓鍵盤使用者也能操作;並在遮罩層也綁定關閉事件,符合多數人「點空白處關閉」的操作習慣。