PhotoSwipe 能做到手機端點擊圖片全螢幕檢視、雙擊再放大、滑動切換、長按存到本機——一連串原生 App 般的操作。官網在 photoswipe.com。
這個版本(1.x 之後的 PhotoSwipe 系列)走的是「自己組 items 陣列」的路子, HTML 那邊不必預先排满 <a> 標籤,設定資料在哪裡、插件就讀哪裡。
<style>
.pnav{ margin-top:30px; text-align:center; line-height:24px; font-size:16px; }
.pnav a{ padding:4px; }
.pnav a.cur{ background:#007bc4; color:#fff; }
.demo{ width:80%; margin:10px auto; }
/* 必要樣式 */
#photos{ width:150px; border:1px solid #d3d3d3; margin:20px auto;
text-align:center; padding:4px; cursor:pointer; position:relative; }
#photos p{ position:absolute; bottom:0; left:0; padding:4px;
background:#000; color:#fff; }
.my-gallery{ width:100%; float:left; }
.my-gallery img{ width:100%; height:auto; }
.my-gallery figure{ display:block; float:left; margin:0 5px 5px 0; width:150px; }
.my-gallery figcaption{ display:none; }
</style><script type="text/javascript">
var openPhotoSwipe = function () {
var pswpElement = document.querySelectorAll('.pswp')[0];
var items = [
{ src: 'images/s1.jpg', w: 800, h: 1142 },
{ src: 'images/s2.jpg', w: 800, h: 1142 },
{ src: 'images/s3.jpg', w: 800, h: 1142 },
{ src: 'images/s4.jpg', w: 800, h: 1142 },
{ src: 'images/s5.jpg', w: 800, h: 1142 }
];
var options = {
history: false,
focus: false,
showAnimationDuration: 0,
hideAnimationDuration: 0
};
var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options);
gallery.init();
};
document.getElementById('photos').onclick = openPhotoSwipe;
</script>每張圖都必須提供 w 與 h。PhotoSwipe 靠這兩個值計算縮放與版面,缺了會導致圖片顯示異常或無法正確放大。若尺寸未知,可先建立 Image 物件等 onload 拿到 naturalWidth 再組陣列。
頁面上要有 .pswp 容器。腳本第一行就是在抓它,這個 DOM 通常由官方提供的 photoswipe.css 與 default-skin 相關結構產生,別忘了引入。
options 裡那三個 0 是刻意關掉動畫的。行動裝置上動畫容易掉幀,直接關掉反而更順;history: false 則是不改寫瀏覽器網址列,避免返回鍵行為干擾頁面。
整體來說,這個版本的接入成本極低:一個陣列、一個 options、一行 init。若你的圖片清單來自接口,只要動態拼出 items 再呼叫 openPhotoSwipe 即可,不必像舊版那樣受限於「初始化前必須把 <a> 排進 DOM」。