滑鼠移到頭像上浮出一張小卡片,移開後過一下子自動收起——這個在 IM 軟體裡很常見的互動,用原生 JavaScript 只要一個計時器就能完成。關鍵在於「延遲隱藏」:與其滑鼠一移開就立刻消失,不如留 0.5 秒緩衝,讓使用者有機會把游標移到彈出的卡片上繼續操作。
1. 頭像移入 → 立刻顯示提示層,並清掉可能殘留的隱藏計時器。
2. 頭像移出 → 啟動 500ms 計時器,時間到才隱藏。
3. 提示層自己也綁同樣的事件:移入時清計時器(避免被收掉),移出時重新計時。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>簡單的類似 QQ 頭像的彈出效果</title>
<style type="text/css">
#oimg{ float:left; margin:10px; }
#msg{ border:solid; width:300px; height:250px; display:none;
float:left; padding:10px; }
</style>
</head>
<body>
<img id="oimg" src="images/show.jpg" />
<div id="msg">啦啦啦啦。。。。。</div>
<script type="text/javascript">
var oid = document.getElementById('oimg');
var omsg = document.getElementById('msg');
var timer = null;
// 頭像:移入顯示,移出延遲隱藏
oid.onmousemove = showMsg;
oid.onmouseout = hideMsg;
// 提示層:移入時取消隱藏,移出時重新計時
omsg.onmousemove = function(){ clearTimeout(timer); };
omsg.onmouseout = hideMsg;
function showMsg(){
if(timer){ clearTimeout(timer); }
omsg.style.display = 'block';
}
function hideMsg(){
timer = setTimeout(function(){
omsg.style.display = 'none';
}, 500);
}
</script>
</body>
</html>
1. 改用 mouseenter / mouseleave。範例用的 mousemove / mouseout 在元素內移動時會反覆觸發,/mouseout 更會在移到子元素時誤觸;mouseenter 與 mouseleave 不具泡泡性,語意也更貼切。
2. 加上淡入淡出。用 CSS transition 或 opacity 漸變替換 display 的硬切換,視覺會柔和很多。
3. 補上定位計算。實際的卡片通常要動態算出相對頭像的座標,用 getBoundingClientRect() 取值後再設 position: fixed,並注意視窗邊界要自動翻轉方向。
4. 記得清理計時器。離開頁面前把 timer 清掉,避免單頁應用中殘留的計時器操作到已移除的節點。