滑鼠移至標題區塊時,右側平滑漸顯詳細說明框;滑鼠移動時提示框跟隨游標位置;移出時淡出消失。適用於新聞列表、產品介紹、資料表格補充說明等場景。
<!DOCTYPE html>
<html>
<head>
<meta charset="gb2312">
<title>漸顯文字提示效果</title>
<style>
.lookMe {
float: left;
margin-right: 10px;
padding: 5px;
width: 90px;
color: #0099FF;
cursor: pointer;
background: #FFFADC;
border: 1px solid #CC6600;
position: relative; /* 關鍵:建立定位基準 */
}
.lookMe span {
display: none;
position: absolute;
left: 110px; top: 0;
padding: 5px;
width: 200px;
color: #CC3300;
background: #FFFADC;
border: 1px solid #CC6600;
opacity: 0; /* 現代透明度寫法 */
filter: alpha(opacity=0); /* IE8- 相容 */
transition: opacity 0.3s ease; /* CSS3 漸變動畫 */
z-index: 100;
white-space: normal;
}
.lookMe:hover span {
display: block;
opacity: 0.8;
filter: alpha(opacity=80);
}
</style>
</head>
<body>
<div class="lookMe">
悶戰120分鐘 點球戰4:2 西班牙破魔咒淘汰意大利
<span>
1、雅虎體育訊 北京時間6月23日,歐洲足球錦標賽在瑞士奧地利繼續進行,
在一場四分之一決賽中,西班牙隊迎來了上屆世界杯冠軍意大利隊,
90分鐘與加時賽雙方均一球未進,在最終的點球大戰中,西班牙4:2擊敗了對手,
昂首挺進四強。
</span>
</div>
<div class="lookMe">
悶戰120分鐘 點球戰4:2 西班牙破魔咒淘汰意大利
<span>2、在一場四分之一決賽中……</span>
</div>
<div class="lookMe">
悶戰120分鐘 點球戰4:2 西班牙破魔咒淘汒意大利
<span>
3、歐洲足球錦標賽在瑞士奧地利繼續進行,在一場四分之一決賽中,
西班牙隊迎來了上屆世界杯冠軍意大利隊……
</span>
</div>
</body>
</html>
上方代碼展示現代最佳實踐:
position: relative 於父元素,position: absolute 於子元素opacity + transition 實現平滑漸顯/漸隱:hover 偽類觸發顯示,無需 JavaScriptz-index 確保提示框浮於其他內容之上原文使用 setInterval 逐步遞增 filter.alpha.opacity,並透過 onmousemove 即時更新 span.style.left/top 跟隨滑鼠。此法雖可運作,但:
filter 屬性,現代瀏覽器不支援<script>
document.querySelectorAll('.lookMe').forEach(el => {
const tooltip = el.querySelector('span');
if (!tooltip) return;
el.addEventListener('mousemove', e => {
const rect = tooltip.getBoundingClientRect();
const vw = window.innerWidth, vh = window.innerHeight;
let left = e.clientX + 15;
let top = e.clientY + 15;
// 防止超出右邊界
if (left + rect.width > vw) left = e.clientX - rect.width - 15;
// 防止超出下邊界
if (top + rect.height > vh) top = e.clientY - rect.height - 15;
tooltip.style.left = left + 'px';
tooltip.style.top = top + 'px';
});
});
</script>
role="tooltip" 於 <span>aria-describedby 關聯觸發元素:focus-within)| 場景 | 建議內容 |
|---|---|
| 新聞標題列表 | 摘要、關鍵字、發布時間 |
| 商品卡片 | 價格、規格、庫存狀態 |
| 資料表格儲存格 | 完整資料、單位說明、備註 |
| 圖表數據點 | 精確數值、時間、趨勢說明 |