九宮格圖片佈局,鼠標懸停時從頂部滑入半透明遮罩層並顯示文字介紹,鼠標離開滑出隱藏。適合相冊、作品集展示。
<dl class="sgw_img">
<dt>
<img src="img1.jpg" alt="">
<div class="box"><h3>標題</h3><p>描述文字</p></div>
</dt>
<dd>
<img src="img2.jpg" alt="">
<div class="box"><h3>標題</h3><p>描述文字</p></div>
</dd>
...
</dl>
.sgw_img dt, .sgw_img dd {
position: relative;
overflow: hidden;
float: left; /* 或 flex/grid 佈局 */
}
.sgw_img .box {
position: absolute;
top: -100%; /* 初始隱藏在上方 */
left: 0;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.7);
color: #fff;
padding: 20px;
box-sizing: border-box;
}
$(function() {
// 大圖區塊 (dt)
$('.sgw_img dt').hover(function() {
$(this).children('.box').stop(true, true).delay(100).animate({top: 0, opacity: 0.8}, 300);
}, function() {
$(this).children('.box').stop(true, true).animate({top: '-100%', opacity: 0}, 200);
});
// 小圖區塊 (dd)
$('.sgw_img dd').hover(function() {
$(this).children('.box').stop(true, true).delay(100).animate({top: 0, opacity: 0.8}, 300);
}, function() {
$(this).children('.box').stop(true, true).animate({top: '-100%', opacity: 0}, 200);
});
});
.stop(true, true):清除動畫隊列並跳至當前動畫末幀,防止快速進出導致動畫堆疊。.delay(100):輕微延遲觸發,避免誤觸閃爍。top 從負值(隱藏)到 0(顯示),配合 opacity 漸變。.sgw_img dt:hover .box,
.sgw_img dd:hover .box {
top: 0;
opacity: 0.8;
transition: top 0.3s ease 0.1s, opacity 0.3s ease 0.1s;
}
/* 初始狀態 */
.sgw_img .box {
top: -100%;
opacity: 0;
transition: top 0.2s ease, opacity 0.2s ease;
}
純 CSS 實現更流暢、無 JS 依賴、性能更好,推薦現代項目優先使用。