「滑鼠靠近就滑出提示層、移開就收起來」是很常見的互動模式,例如商品快速預覽、導覽提示。核心只有兩個事件: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);
}
event.relatedTarget 是否仍在容器內,或改用滑鼠移入/移出整個容器來判斷。