使用photoswipe的一些筆記

2024-04-12
PhotoSwipe是一個JS套件,主要是用來把圖片放大縮小用的一個效果,他支持觸控及滑鼠事件,擴展性不錯

使用的時候有遇到一個問題,就是他需要預先指定圖片尺寸在data標籤中,這其實有點麻煩,因為通常圖片尺寸不太有機會是寫死在標籤上的,所以作為一個好用的套件,這部分最好也給他自動化一下會比較方便使用,以下是使用的一個範例:

HTML結構為下:
<div class="photoswip">
         <a href="圖片放大後的連結" target="_blank">
                  <img src="原始圖片連結" />
          </a>
        .
        .
        .
</div>

CSS放在head
<link rel="stylesheet" href="自己主機的路徑/photoswipe/dist/photoswipe.css">

JS放在頁面尾巴
<script type="module">
        import PhotoSwipeLightbox from '自己主機的路徑/photoswipe/dist/photoswipe-lightbox.esm.js';
        const targetWraperClass = '.photoswipe';
        const initScale = 2;
        const weelZoom = true;
       
        var lists = document.querySelectorAll(`${targetWraperClass} a`);
        lists.forEach(item => {
            const img = new Image();
            img.src = item.attributes.href.value;
            img.onload = () => {
                item.setAttribute('data-pswp-width', img.naturalWidth*initScale);
                item.setAttribute('data-pswp-height', img.naturalHeight*initScale);
            }
        });
        const lightbox = new PhotoSwipeLightbox({
            gallery: targetWraperClass,
            children: 'a',
            pswpModule: () => import('自己主機的路徑/photoswipe/dist/photoswipe.esm.js'),
            wheelToZoom: weelZoom,
            getViewportSizeFn: function(options, pswp) {
                return {
                x: document.documentElement.clientWidth,
                y: window.innerHeight
                };
            },
        });
        lightbox.init();
    </script>

JS我就直接使用module的方式來引入了,反正現在所有的瀏覽器幾乎都支援,那些不支援的,就算放棄他也沒關係啦!

我就不寫註解了,總之這種做法簡單來說,就是透過我們把需要用photoswipe作放大縮小效果的圖片,做成一個清單,也就是lists,然後我們在透過代碼來將每一張圖片建立一個Image物件,將其中的尺寸自動算出並帶入data標籤,我這邊有做一個參數initScale,他可以用來微調放大圖的比例,如果放大圖實在是太大張,那當你放大的時候,他會很大,反之則會很小。所以可以透過這個參數來進行統一調整。

大概就是這樣,其他Api選項可以到他的手冊進行查閱: 
PhotoSwipe手冊

Contact

Github

Codepen

歡迎參觀我的賣場
© 2013 Copyright Digishot Web | Design Tools
Visitors【640353】
digishot webdesign studio