這個效果在電商與作品集網站很常見:點縮圖,畫面暗下來,大圖置中浮現,點關閉回到原狀。原理不複雜——一個遮罩層加上一個置中的圖片容器,再處理捲動鎖定就好。
* { margin: 0; padding: 0; }
.tab_bg {
display: none;
width: 100%; height: 100%;
background: #282829;
z-index: 99;
position: absolute;
}
.tab_img { width: 100px; height: 100px; margin: 20px; }
.tab_img img { width: 100%; height: 100%; }
.bigImg {
display: none;
width: 300px; height: 300px;
z-index: 999;
position: absolute;
left: 50%;
margin-top: -150px;
margin-left: -150px;
}
.bigImg img { width: 100%; height: 100%; }
.close {
display: none;
width: 20px; height: 20px;
border-radius: 100%;
border: 1px solid #ccc;
text-align: center;
cursor: pointer;
position: absolute;
right: 10px; top: 10px;
z-index: 999;
color: #fff;
}
li { height: 300px; }
置中的技巧值得留意:left: 50% 讓元素左緣落在畫面正中,再用負的 margin-left 把整個元素往左推回一半寬度,視覺上就真正放正了。z-index 分兩層——遮罩 99、圖片與關閉鈕 999——確保後者永遠在上面。
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <div class="tab_bg"> <div class="close">x</div> </div> <ul> <li>111</li> <li>111</li> <li>111</li> </ul> <table> <tr> <td>1</td> <td><div class="tab_img tab_img1"><img src="2.jpg" alt="" /></div></td> </tr> <tr> <td>2</td> <td><div class="tab_img tab_img2"><img src="3.jpg" alt="" /></div></td> </tr> <tr> <td>3</td> <td><div class="tab_img tab_img3"><img src="1.jpg" alt="" /></div></td> </tr> </table> </body> </html>
var $height = $(window).height();
$(".tab_bg").height($height); // 遮罩至少覆蓋整個視窗
function imgEnlarge(small) {
$(small).on("click", function () {
// 動態組出大圖容器
var $big = document.createElement("div");
$($big).attr("class", "bigImg").appendTo($("body"));
var $img = document.createElement("img");
$($img).attr("src", $(this).find("img").attr("src")).appendTo($big);
$(this).css("display", "none");
$(".tab_bg").css("display", "block");
$(".close").css("display", "block");
$($big).fadeIn();
// 鎖住捲軸,避免背景滑動
$(window).bind("scroll", function () { return false; });
var top1 = $(window).scrollTop();
$(window).scrollTop(top1);
$(".tab_bg").css("top", top1);
$("body").css("overflow", "hidden");
// 依視窗高度計算置中位置
$(".bigImg").css("top", top1 + $height / 2);
});
$(".close").on("click", function () {
$(this).css("display", "none");
$(small).css("display", "block");
$(".tab_bg").css("display", "none");
$(".bigImg").css("display", "none");
$("body").css("overflow", "auto");
});
}
$(".tab_img").each(function () {
imgEnlarge($(this));
});
1. 遮罩高度用 fixed 更好。這裡用 position: absolute 加手動計算 top,是為了配合當下的捲動位置。若改用 position: fixed,遮罩會自動固定在視井上,不必處理 top 偏移,程式碼能少一半。
2. 每次點擊都動態建元素會累積垃圾。比較好的做法是把 .bigImg 寫在 HTML 裡,點擊時只更新 img 的 src 並切換顯示,關閉時清空 src。
3. 缺少鍵盤支援。實務上應該監聽 Esc 鍵關閉,並為縮圖加上 alt 屬性,這是可及性的基本要求。
4. 遮罩點擊關閉。目前只有右上角的小叉能關。加上「點擊遮罩空白處也關閉」會更符合使用者習慣——但要注意别讓點擊事件冒泡到圖片上。