滑鼠移至連結文字,鄰近位置彈出預定義的 div 提示層;滑鼠移出連結或提示層均自動隱藏。適用於商品預覽、詞彙解釋、操作提示等場景。
<style>
#tooltip { display:none; width:315px; height:180px; background:#CCC; border:1px solid #333; padding:12px; text-align:center; position:absolute; z-index:999; }
</style>
<script>
function showTip() { document.getElementById('tooltip').style.display = 'block'; }
function hideTip() { document.getElementById('tooltip').style.display = 'none'; }
</script>
<a href="#" onmouseover="showTip()" onmouseout="hideTip()">將滑鼠移至此處</a>
<div id="tooltip" onmouseover="showTip()" onmouseout="hideTip()">
提示內容:可放圖片、文字、連結...
</div>
onmouseover="showTip()" 讓滑鼠移入提示層時不會消失,體驗更友善。e.clientX/Y + scrollLeft/Top)動態設定 left/top,避免遮蔽內容或超出視窗。setTimeout(hideTip, 200) 緩衝,避免滑鼠在連結與提示層間穿梭時閃爍。<style>
.tooltip { position:relative; cursor:help; }
.tooltip::after {
content: attr(data-tip);
position:absolute; left:50%; bottom:120%; transform:translateX(-50%);
width:200px; padding:8px; background:#333; color:#fff; border-radius:4px; font-size:12px;
opacity:0; pointer-events:none; transition:opacity 0.2s; white-space:normal;
}
.tooltip:hover::after { opacity:1; }
</style>
<span class="tooltip" data-tip="這是提示內容,支援換行與樣式">懸停看提示</span>
零 JS、效能極佳、自動隨元素定位、支援 RWD,現代專案首選。