本文介紹一個輕巧的 jQuery 圖片展示方案。未點擊時,縮圖整齊排列成一列;點擊任一張縮圖,該圖會平滑放大並顯示說明文字;按下關閉鈕後再縮回原本的縮圖形態。
<head> 中依序引入 jquery.js 與 photorevealer.js,以及對應的 CSS。photorevealer.js 中控制高度的那個數值。$(document).ready(function(){
$('.photo_slider').each(function(){
var $this = $(this).addClass('photo-area');
var $img = $this.find('img');
var $info = $this.find('.info_area');
var opts = {};
// 圖片載入後才知道真實尺寸
$img.load(function(){
opts.imgw = $img.width();
opts.imgh = $img.height();
});
// 記錄收合狀態的原始尺寸
opts.orgw = $this.width();
opts.orgh = $this.height();
// 用負 margin 把圖片定位到縮圖框中央
$img.css({ marginLeft: "-150px", marginTop: "-150px" });
// 動態包上容器,並加上「更多資訊」與「關閉」兩個控制元素
var $wrap = $('<div class="photo_slider_img">').append($img).prependTo($this);
var $open = $('<a href="#" class="more_info">More Info ></a>').appendTo($this);
var $close = $('<a class="close">Close</a>').appendTo($info);
opts.wrapw = $wrap.width();
opts.wraph = $wrap.height();
// 展開:外框、內容器、圖片三者同步放大
$open.click(function(){
$this.animate({
width: opts.imgw,
height: opts.imgh + 30,
borderWidth: "10"
}, 600);
$open.fadeOut();
$wrap.animate({ width: opts.imgw, height: opts.imgh }, 600);
$(".info_area", $this).fadeIn();
$img.animate({ marginTop: "0px", marginLeft: "0px" }, 600);
return false;
});
// 收合:全部還原成初始狀態
$close.click(function(){
$this.animate({
width: opts.orgw,
height: opts.orgh,
borderWidth: "1"
}, 600);
$open.fadeIn();
$wrap.animate({ width: opts.wrapw, height: opts.wraph }, 600);
$img.animate({ marginTop: "-150px", marginLeft: "-150px" }, 600);
$(".info_area", $this).fadeOut();
return false;
});
});
});
為什麼要用負 margin?縮圖狀態下,圖片實際尺寸遠大於容器,用 marginLeft: -150px 把圖片往左上推,剛好讓容器顯示圖片的中央區域。展開時把 margin 歸零,圖片就回到完整顯示的位置——這是全篇最巧妙的一手,用純定位完成「裁切 → 完整」的視覺轉換。
為什麼要動態包一層 $wrap?外框 $this 負責邊框與整體尺寸,內層 $wrap 負責裁切視窗。分成兩層後,動畫期間外框與內容器可以各自以不同節奏縮放,視覺上更流暢,也避免 overflow:hidden 直接作用在外框時產生的對齊問題。
600 毫秒這個數字。所有 animate 都要用同一個 duration,否則會出現「框放大了,圖片還沒跟上」的破綻。實務上把時間抽成變數統一管理會更好維護。
$img.load() 換成 .on('load'),並加上 complete 判斷,避免圖片從快取載入時 load 事件已經錯過。