DIV CSS 佈局教程網

一個滑鼠移入滑出層效果的實作
編輯:關於JavaScript     

「滑鼠靠近就滑出提示層、移開就收起來」是很常見的互動模式,例如商品快速預覽、導覽提示。核心只有兩個事件:onmouseover 與 onmouseout。

範例程式碼

<!DOCTYPE html>
<html>
<head>
<title>滑動彈出層</title>
<style type="text/css">
  #div1 { background: #CCC; width: 500px; height: 400px; display: none; }
</style>
</head>
<body>
<label>
  <input type="checkbox" onmouseover="shouhui()" onmouseout="fangzou()" />滑鼠靠近後查看
</label>
</body>
</html>

其中 shouhui() 負責把 div1 的 display 改為 block 並啟動滑入動畫,fangzou() 則反向操作。若不寫動畫,最基本的版本只要切換 display 即可:

function shouhui() { document.getElementById('div1').style.display = 'block'; }
function fangzou() { document.getElementById('div1').style.display = 'none'; }

要做出「滑動」感覺的關鍵

單純顯示隱藏顯得生硬,加一點位移會好很多。做法是用 opacity 或 height 做補間:

var timer = null;
function slide(open) {
  var el = document.getElementById('div1');
  var step = 10, h = 0;
  clearInterval(timer);
  el.style.display = 'block';
  timer = setInterval(function () {
    if (open) {
      h += step;
      if (h >= 400) { h = 400; clearInterval(timer); }
    } else {
      h -= step;
      if (h <= 0) { h = 0; el.style.display = 'none'; clearInterval(timer); }
    }
    el.style.height = h + 'px';
    el.style.overflow = 'hidden';
  }, 20);
}

幾個容易踩到的細節

  • 事件冒泡:如果弹出层是 triggered 元素的子節點,滑鼠移到層上會觸發父元素的 onmouseout,導致層閃一下消失。解法是在 onmouseout 裡判斷 event.relatedTarget 是否仍在容器內,或改用滑鼠移入/移出整個容器來判斷。
  • 不要用 onmouseover / onmouseout,改用 mouseenter / mouseleave:後者不會因內部元素切換而觸發,正是為這個場景設計的。
  • display 與 visibility 的差別:display:none 不佔版面,visibility:hidden 佔位。彈出層通常用 display,但如果會造成版面跳動,可考慮 visibility 或 opacity。
  • 無障礙:純滑鼠效果對鍵盤使用者不友善,建議同時綁定 focus / blur,讓 Tab 聚焦時也能展開。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved