DIV CSS 佈局教程網

頁面右下角彈出提示框:原生 JS 實作與其陷阱
編輯:JavaScript綜合知識     

「您有新消息」從右下角滑出來的提示框,是早期網站的常見配置。這份實作用純 JavaScript 完成,包含滑出動畫、遮罩層與置中詳情視窗。

CSS 定位

* { margin: 0px; padding: 0px; }   // 用萬用選擇器歸零
html, body { height: 100%; }   // 讓百分比高度有參照
body { font-size: 14px; line-height: 24px; }

#tip {
  position: absolute;
  right: 0px;   bottom: 0px;
  height: 0px;   width: 180px;
  border: 1px solid #CCCCCC;
  background-color: #eeeeee;
  padding: 1px;
  overflow: hidden;   // 關鍵:高度變小但未消失時,內容不溢出
  display: none;
  font-size: 12px;
  z-index: 10;
}

#shadow {
  position: absolute;   width: 100%;   height: 100%;
  background-color: #000000;
  z-index: 11;   // 比提示框高
  filter: Alpha(Opacity=70);   // IE 的半透明寫法
  display: none;
}

#detail {
  width: 500px;   height: 200px;   border: 3px double #ccc;
  background-color: #FFFFFF;
  position: absolute;   z-index: 30;   // 最高層
  display: none;   left: 30%;   top: 30%
}

三層 z-index(10 / 11 / 30)建立了清楚的堆疊關係:提示框最底、遮罩在中、詳情視窗在最上。overflow: hidden 是滑出動畫能成立的關鍵——高度從 0 開始增加時,超過的部分被裁掉,視覺上就像內容從邊緣逐漸露出。

用 html, body { height: 100% } 是為了讓遮罩的 height: 100% 有東西可以參照。少了這行,遮罩會塌成零高度。這也是為什麼用 position: fixed 會更省事——它直接以視窗為參照,不必依賴父元素高度。

JavaScript 動畫

var handle;

function start() {
  var obj = document.getElementById("tip");
  if (parseInt(obj.style.height) == 0) {
    obj.style.display = "block";
    handle = setInterval("changeH('up')", 2);
  } else {
    handle = setInterval("changeH('down')", 2);
  }
}

function changeH(str) {
  var obj = document.getElementById("tip");
  if (str == "up") {
    if (parseInt(obj.style.height) > 200) clearInterval(handle);
    else obj.style.height = (parseInt(obj.style.height) + 8).toString() + "px";
  }
  if (str == "down") {
    if (parseInt(obj.style.height) < 8) { clearInterval(handle); obj.style.display = "none"; }
    else obj.style.height = (parseInt(obj.style.height) - 8).toString() + "px";
  }
}

這是最經典的「定時器 + 數值遞增」動畫:每 2 毫秒呼叫一次,高度加減 8px,直到抵達 200 或 0 為止。handle 存的是 interval 的 id,用來在到達終點時清除自己——少了這步,定時器會永遠跑下去。

start() 用「目前高度是否為 0」判斷要往上還是往下,所以同一個函式可以當作切換開關用。這是省事的寫法,但也意味著它沒有真正的「開啟中」狀態——連續快速點擊可能導致多個 interval 同時存在。

顯示與還原詳情視窗

function showwin() {
  document.getElementsByTagName("html")[0].style.overflow = "hidden";  // 鎖住捲軸
  start();
  document.getElementById("shadow").style.display = "block";
  document.getElementById("detail").style.display = "block";
}

function recover() {
  document.getElementsByTagName("html")[0].style.overflow = "auto";   // 還原捲軸
  document.getElementById("shadow").style.display = "none";
  document.getElementById("detail").style.display = "none";
}

把 html 的 overflow 設為 hidden 是為了避免背景捲動—— modal 視窗開啟時頁面應該被鎖住。這個細節很多實作會漏,結果使用者在彈窗上滾輪,背景的內容跟著跑掉。

HTML 與自動輪播

<div id="shadow"></div>
<div id="detail"></div>
<div id="tip">
  <h1><a href="javascript:void(0)" onclick="start()">×</a>您有新消息</h1>
  <p><a href="javascript:void(0)" onclick="showwin()">點擊這裡查看詳細</a></p>
</div>

<script language="JavaScript">
window.attachEvent("onload", myTimer);   // 綁到 onload
function myTimer() {
  start();
  window.setTimeout("myTimer()", 6000);   // 每 6 秒循環一次
}
</script>

href="javascript:void(0)" 是那個年代的常見寫法,用來讓連結可聚焦但不跳頁。今天更好的做法是直接用 <button>,並在 CSS 裡重設樣式。

這份程式碼的問題清單

attachEvent 只支援 IE。標準瀏覽器要用 addEventListener('load', myTimer)。混用兩者是當時的常態,但更好的做法是寫一個小 wrapper,或直接改用 onload 屬性。

parseInt 對空字串回傳 NaN。obj.style.height 在樣式由外部 CSS 設定時可能是空字串,parseInt("") 得到 NaN,後續比較全部失效。應改用 parseFloat(obj.style.height) || 0。

setInterval 的字串寫法。setInterval("changeH('up')", 2) 相當於 eval,效能差且不利除錯。應寫成 setInterval(function(){ changeH('up'); }, 2)。

2 毫秒的間隔太激進。瀏覽器對 setTimeout 有最小延遲限制(實作上通常被夾到 4ms 以上),而且每格改樣式都觸發重排。用 CSS transition 一行就能做到同樣效果,而且由合成器處理,順順的。

缺少無障礙處理。彈出提示應該用 role="alert" 或 aria-live="polite" 讓螢幕閱讀器播報;遮罩視窗應該用 role="dialog" 加 aria-modal="true",並把焦點移入視窗、關閉後歸還焦點。少了這些,鍵盤與閱讀器使用者會完全不知道發生了什麼。

點擊遮罩無法關閉。使用者期待點背景就能關掉視窗,這裡沒有實作,也沒有 ESC 鍵關閉。

用 CSS 重寫動畫部分

#tip {
  position: fixed;   right: 0;   bottom: 0;   width: 180px;
  transform: translateY(100%);   // 先藏在視窗外
  transition: transform .3s ease;
}
#tip.open { transform: translateY(0); }

function toggleTip() {
  var tip = document.getElementById('tip');
  var open = tip.classList.toggle('open');
  tip.setAttribute('aria-hidden', !open);
}

四行取代原本三十行的定時器邏輯,而且更順、更省電、更容易維護。用 transform 而非 height 是重點——transform 只觸發合成,不觸發重排,效能差異在長時間執行的動畫上非常明顯。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved