在電商或圖集網站中,「點擊查看大圖」是非常實用的功能。本文透過 jQuery 實現一個帶遮罩層的大圖查看器,並支持點擊關閉與窗口自適應。
/*查看大圖*/
var screenheight = $(window).height();
var screenwidth = $(window).width();
var loadCSS = function(){
var screenwidth = $(window).width();
var screenheight = $(window).height();
$("div.lookBigPicture").css({"left":screenwidth*0.2,"top":screenheight*0.15+$(document).scrollTop(), "width":screenwidth*0.6,"height":screenheight*0.7});
$("img.bigImg").css({"max-width":(screenwidth*0.6 - 30),"max-height":screenheight*0.7-40});
$("img.bigImg").load(function(){
$("img.bigImg").css("top",(screenheight*0.7 - 30 - $("img.bigImg").height())*0.5 + 30);
});
$.log("$(document).height():"+$(document).height());
};
$("a#bigPic").click(function(){
str = $("img[img-size]").attr("src");
$("body").append("<div class='grey'></div>");//灰色底層
$("body").append("<div class='lookBigPicture'><span class='protoPic'><a z-index='20001' target='_blank' href='"+str+"'>查看原圖</a></span><a href='javascript:;' class='bigpicclose' title='關閉'>×</a><img class='bigImg' src='"+str+"'/></div>");
$("div.grey").css("height",$(document).height());
loadCSS();
$("body").css({overflow:"hidden"}); //禁用滾動條
});
$("body").delegate("div.grey,a.bigpicclose","click",function(){
$("body").css({overflow:"visible"}); //恢復滾動條
$("div.lookBigPicture").remove();
$("div.grey").remove();
});
//當瀏覽器窗口大小改變時
$(window).resize(function () { loadCSS(); });
/***遮罩層****/
.grey { background: #000; display: block; z-index: 1000; width: 100%; position: absolute; filter: alpha(opacity:50); opacity: 0.5; top: 0; left: 0; }
.lookBigPicture { border: #000 solid 1px; position: absolute; z-index: 2000; text-align: center; background: black; }p>
.bigImg { margin-left: auto; margin-right: auto; position: relative; }
.bigpicclose { position: absolute; width: 36px; height: 36px; font-size: 0; z-index: 20001; top: -18px; right: -18px; background: url("https://img.t.sinajs.cn/t5/style/images/layer/multipic_ico.png?id=20131018174500") 0 0 no-repeat; }
.protoPic { position: absolute; display: inline-block; height: 30px; top: 10px; right: 50px; overflow: hidden; cursor: pointer; color: #F8F8F8; text-shadow: 0 1px 0 rgba(0, 0, 0, .5); }
<p pic-choice style="display: none;">
<em class="W_ico12"></em><a href="javascript:;" id="hidePic">收起</a>
<em class="lookbigicn"></em><a href="javascript:;" id="bigPic">查看大圖</a>
</p>
整個功能的關鍵在於:點擊時動態創建遮罩層與大圖容器,根據窗口尺寸計算居中位置,並在打開時禁用滾動條、關閉時恢復,同時監聽窗口 resize 事件以保持自適應。