點縮圖、看大圖,是最經典的圖片走廊行為。這一篇我們把它做成外掛,順帶完成一個通用的「置中」外掛,兩個湊起來剛好是一套可重複使用的小工具。
(function ($) {
$.fn.gallery = function () {
return this.each(function () {
var self = $(this);
self.click(function () {
});
});
}
})(jQuery);
<script type="text/javascript" src="Scripts/jquery-1.6.2.js"></script>
<script type="text/javascript" src="Scripts/jquery.gallery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('img').gallery();
});
</script>
</head>
<body>
<img src="Images/orderedList1.png" alt="" />
<img src="Images/orderedList2.png" alt="" />
<img src="Images/orderedList3.png" alt="" />
這裡有個實用的技巧:並不是把原圖放大,而是用 jQuery 的 clone() 複製一份節點,改 id、改尺寸,插到 body 底下當大圖。原圖完全不受影響,關閉時只要把 clone 的節點移除即可。
(function ($) {
$.fn.gallery = function () {
return this.each(function () {
// 存成 self,避免不同函式上下文中 this 指向不同物件
var self = $(this);
// 統一縮圖高度(可依需求調整,或開成 options)
self.height(100);
self.click(function () {
// 每次點擊先清掉上一張大圖
$('#myImgGallery').remove();
self.clone()
.attr('id', 'myImgGallery')
.height($(window).height() / 2) // 大圖高度取視窗可用高度的一半
.css({ position: 'absolute' })
.prependTo('body')
// 一定要先插入 body 再呼叫 center,否則寬高都是 0
.center()
.click(function () {
$(this).remove(); // 點大圖即可關閉
});
});
});
};
// 通用的置中外掛
$.fn.center = function () {
return this.each(function () {
$(this).css({
position: 'absolute',
top: ($(window).height() - $(this).height()) / 2 + $(window).scrollTop() + 'px',
left: ($(window).width() - $(this).width()) / 2 + $(window).scrollLeft() + 'px'
});
});
};
})(jQuery);
順序很重要:clone() 之後必須先 prependTo('body'),才能呼叫 center()。因為游离在 DOM 之外的節點,width() 與 height() 都會回傳 0,算出來的位置自然是錯的。
要加上滾動距離:置中計算裡的 $(window).scrollTop() 與 scrollLeft() 常被遺漏。少了它,頁面捲動後大圖就會跑到錯誤的位置——因為 absolute 定位是相對於文件而非視窗。若希望大圖永遠固定在視窗中央,把 position 改成 fixed 並拿掉這兩項即可(必要時再補 z-index 確保它在最上層)。
這兩個外掛合起來示範了一個很實用的組合哲學:把「置中」這種通用行為獨立成一個外掛,讓 gallery、彈跳視窗、提示框都能重複使用,而不是每個地方各寫一次座標計算。完整展示可參考 jQuery.plugin.gallery 的 demo。