てがろぐでPhotoSwipeを使う

てがろぐの画像拡大表示にPhotoSwipe v5を使う。

  • 投稿内の複数画像をスワイプで切替
  • 「画像クリックで閉じる」オプション
  • 余計なフレームやアニメーション無し
  • △ data属性で画像サイズ指定必須
    • JSで自動付与対応
  • △ マウスホイールで画像切替非対応
    • スクリプト改変で実装

動作サンプル(稼働中のてがろぐ)

実装

基本

  1. skin-cover.html<head>内でCDNを読み込む
    • 又はGithubから3ファイルDLして自鯖に置く
<script src="https://cdn.jsdelivr.net/npm/photoswipe@5.3.7/dist/umd/photoswipe.umd.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@5.3.7/dist/umd/photoswipe-lightbox.umd.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/photoswipe@5.3.7/dist/photoswipe.min.css" rel="stylesheet">
  1. </body>直前にコードを追加
<script type="text/javascript">
	var lightbox = new PhotoSwipeLightbox({
		gallery: '.comment',
		children: 'a.imagelink',
		imageClickAction: 'close',
		tapAction: 'close',
		bgClickAction: 'close',
		showHideAnimationType: 'fade',
		loop: false,
		bgOpacity: 0.5,
		pswpModule: PhotoSwipe
	});
	lightbox.init();
</script>

imageClickAction: 'close'で画像クリックで閉じる設定。

data属性追加

<script type="text/javascript">
	document.addEventListener('DOMContentLoaded', function () {
		const galleries = document.querySelectorAll('.imagelink');
		galleries.forEach((el) => {
			loadImage(el.href).then(img => {
				el.setAttribute('data-pswp-width', img.naturalWidth);
				el.setAttribute('data-pswp-height', img.naturalHeight);
			});
		});
	});

	function loadImage(src) {
		return new Promise((resolve, reject) => {
			const img = new Image();
			img.onload = () => resolve(img);
			img.onerror = (e) => reject(e);
			img.src = src;
		});
	}
</script>

処理完了前に画像をクリックされる可能性がある。現在はtegalog.cgiを直接編集しているが、変更箇所が多く本体更新の度に面倒。

マウスホイールで画像切替

  1. dist/photoswipe.esm.jsをDLし、以下の箇所に//ホイール処理//endを追加
      _onWheel(e) {
        e.preventDefault();
        const { currSlide } = this.pswp;
        let { deltaX, deltaY } = e;
    
    	//ホイール処理
    	if (e.wheelDelta > 0) {
    		pswp.prev();
    	} else {
    		pswp.next();
    	}
    	//end
    
        if (!currSlide) {
          return;
        }
    1. 基本-2で追加したコードのpswpModule: PhotoSwipeを以下に変更 (パスは適宜変更)
    pswpModule: () => import('./photoswipe.esm.js')

    UI調整

    • てがろぐ用CSSに以下を追加
    .pswp__top-bar .pswp__button.pswp__button--zoom
    .pswp__top-bar .pswp__button.pswp__button--close
    	display: none
    
    .pswp__counter
    	position: fixed
    	right: 5%
    	bottom: 5%

    ズーム・閉じるボタンの非表示とカウント位置調整。


    参考