【JavaScript】スワイプができるlightbox系プラグイン『PhotoSwipe』の実装サンプル集

【JavaScript】スワイプができるlightbox系プラグイン『PhotoSwipe』の実装サンプル集
うまく動きませんー
うまく動かしましょうー

機能をフルに使う

See the Pen 【JavaScript】スワイプができるlightbox系プラグイン『PhotoSwipe』サンプル(デフォルト) by 125naroom (@125naroom) on CodePen.

HTMLとJavaScriptはこちら

HTML

<div class="ps_area photoswipe_gallery">
  <a href="https://125naroom.com/wp/wp-content/uploads/2015/02/sora01.jpg" data-size="600x600" data-med="https://125naroom.com/wp/wp-content/uploads/2015/02/sora01.jpg" data-med-size="600x600" data-author="125naroom">
    <img src="https://125naroom.com/wp/wp-content/uploads/2015/02/sora01.jpg" alt=""/>
    <figure>sora 1</figure>
  </a>
  <a href="https://125naroom.com/wp/wp-content/uploads/2015/02/sora02.jpg" data-size="600x600" data-med="https://125naroom.com/wp/wp-content/uploads/2015/02/sora02.jpg" data-med-size="600x600" data-author="125naroom">
    <img src="https://125naroom.com/wp/wp-content/uploads/2015/02/sora02.jpg" alt=""/>
    <figure>sora 2</figure>
  </a>
  <a href="https://125naroom.com/wp/wp-content/uploads/2015/02/sora03.jpg" data-size="600x600" data-med="https://125naroom.com/wp/wp-content/uploads/2015/02/sora03.jpg" data-med-size="600x600" data-author="125naroom">
    <img src="https://125naroom.com/wp/wp-content/uploads/2015/02/sora03.jpg" alt=""/>
    <figure>sora 3</figure>
  </a>
  <a href="https://125naroom.com/wp/wp-content/uploads/2015/02/sora04.jpg" data-size="600x600" data-med="https://125naroom.com/wp/wp-content/uploads/2015/02/sora04.jpg" data-med-size="600x600" data-author="125naroom">
    <img src="https://125naroom.com/wp/wp-content/uploads/2015/02/sora04.jpg" alt=""/>
    <figure>sora 4</figure>
  </a>
  <a href="https://125naroom.com/wp/wp-content/uploads/2015/02/sora05.jpg" data-size="600x600" data-med="https://125naroom.com/wp/wp-content/uploads/2015/02/sora05.jpg" data-med-size="600x600" data-author="125naroom">
    <img src="https://125naroom.com/wp/wp-content/uploads/2015/02/sora05.jpg" alt=""/>
    <figure>sora 5</figure>
  </a>
</div>
 
<!--モーダル用、置き場は自由ですが、フッター近くのほうがソースが綺麗かなと-->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="pswp__bg"></div>
  <div class="pswp__scroll-wrap">
    <div class="pswp__container">
      <div class="pswp__item"></div>
      <div class="pswp__item"></div>
      <div class="pswp__item"></div>
    </div>
    <div class="pswp__ui pswp__ui--hidden">
      <div class="pswp__top-bar">
        <div class="pswp__counter"></div>
        <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
        <button class="pswp__button pswp__button--share" title="Share"></button>
        <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
        <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
        <div class="pswp__preloader">
          <div class="pswp__preloader__icn">
            <div class="pswp__preloader__cut">
              <div class="pswp__preloader__donut"></div>
            </div>
          </div>
        </div>
      </div>
      <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
        <div class="pswp__share-tooltip"></div>
      </div>
      <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)"></button>
      <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)"></button>
      <div class="pswp__caption">
        <div class="pswp__caption__center"></div>
      </div>
    </div>
  </div>
</div>

JavaScript

// .photoswipe_gallery
(function() {
  var initPhotoSwipeFromDOM = function(gallerySelector) {
 
    var parseThumbnailElements = function(el) {
      var thumbElements = el.childNodes,
          numNodes = thumbElements.length,
          items = [],
          el,
          childElements,
          thumbnailEl,
          size,
          item;
 
      for(var i = 0; i < numNodes; i++) {
        el = thumbElements[i];
 
        // include only element nodes 
        if(el.nodeType !== 1) {
          continue;
        }
 
        childElements = el.children;
 
        size = el.getAttribute('data-size').split('x');
 
        // create slide object
        item = {
          src: el.getAttribute('href'),
          w: parseInt(size[0], 10),
          h: parseInt(size[1], 10),
          author: el.getAttribute('data-author')
        };
 
        item.el = el; // save link to element for getThumbBoundsFn
 
        if(childElements.length > 0) {
          item.msrc = childElements[0].getAttribute('src'); // thumbnail url
          if(childElements.length > 1) {
            item.title = childElements[1].innerHTML; // caption (contents of figure)
          }
        }
 
 
        var mediumSrc = el.getAttribute('data-med');
        if(mediumSrc) {
          size = el.getAttribute('data-med-size').split('x');
          // "medium-sized" image
          item.m = {
            src: mediumSrc,
            w: parseInt(size[0], 10),
            h: parseInt(size[1], 10)
          };
        }
        // original image
        item.o = {
          src: item.src,
          w: item.w,
          h: item.h
        };
 
        items.push(item);
      }
 
      return items;
    };
 
    // find nearest parent element
    var closest = function closest(el, fn) {
      return el && ( fn(el) ? el : closest(el.parentNode, fn) );
    };
 
    var onThumbnailsClick = function(e) {
      e = e || window.event;
      e.preventDefault ? e.preventDefault() : e.returnValue = false;
 
      var eTarget = e.target || e.srcElement;
 
      var clickedListItem = closest(eTarget, function(el) {
        return el.tagName === 'A';
      });
 
      if(!clickedListItem) {
        return;
      }
 
      var clickedGallery = clickedListItem.parentNode;
 
      var childNodes = clickedListItem.parentNode.childNodes,
          numChildNodes = childNodes.length,
          nodeIndex = 0,
          index;
 
      for (var i = 0; i < numChildNodes; i++) {
        if(childNodes[i].nodeType !== 1) { 
          continue; 
        }
 
        if(childNodes[i] === clickedListItem) {
          index = nodeIndex;
          break;
        }
        nodeIndex++;
      }
 
      if(index >= 0) {
        openPhotoSwipe( index, clickedGallery );
      }
      return false;
    };
 
    var photoswipeParseHash = function() {
      var hash = window.location.hash.substring(1),
          params = {};
 
      if(hash.length < 5) { // pid=1
        return params;
      }
 
      var vars = hash.split('&');
      for (var i = 0; i < vars.length; i++) {
        if(!vars[i]) {
          continue;
        }
        var pair = vars[i].split('=');  
        if(pair.length < 2) {
          continue;
        }           
        params[pair[0]] = pair[1];
      }
 
      if(params.gid) {
        params.gid = parseInt(params.gid, 10);
      }
 
      return params;
    };
 
    var openPhotoSwipe = function(index, galleryElement, disableAnimation, fromURL) {
      var pswpElement = document.querySelectorAll('.pswp')[0],
          gallery,
          options,
          items;
 
      items = parseThumbnailElements(galleryElement);
 
      // define options (if needed)
      options = {
 
        //ここからオプション追加
        //          showHideOpacity: true,
        //          bgOpacity: 1,
        //          spacing: 0.12,
        //          maxSpreadZoom: 2,
        //          loop: true,
        //          pinchToClose: true,
        //          closeOnScroll: true,
        //          closeOnVerticalDrag: true,
        //          preload: [1,1],
        //ここまでオプション追加
 
        galleryUID: galleryElement.getAttribute('data-pswp-uid'),
 
        getThumbBoundsFn: function(index) {
          // See Options->getThumbBoundsFn section of docs for more info
          var thumbnail = items[index].el.children[0],
              pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
              rect = thumbnail.getBoundingClientRect(); 
 
          return {x:rect.left, y:rect.top + pageYScroll, w:rect.width};
        },
 
        addCaptionHTMLFn: function(item, captionEl, isFake) {
          if(!item.title) {
            captionEl.children[0].innerText = '';
            return false;
          }
          captionEl.children[0].innerHTML = item.title +  '<br/><small>Photo: ' + item.author + '</small>';
          return true;
        }
 
      };
 
 
      if(fromURL) {
        if(options.galleryPIDs) {
          // parse real index when custom PIDs are used 
          // http://photoswipe.com/documentation/faq.html#custom-pid-in-url
          for(var j = 0; j < items.length; j++) {
            if(items[j].pid == index) {
              options.index = j;
              break;
            }
          }
        } else {
          options.index = parseInt(index, 10) - 1;
        }
      } else {
        options.index = parseInt(index, 10);
      }
 
      // exit if index not found
      if( isNaN(options.index) ) {
        return;
      }
 
 
 
      if(disableAnimation) {
        options.showAnimationDuration = 0;
      }
 
      // Pass data to PhotoSwipe and initialize it
      gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
 
      // see: http://photoswipe.com/documentation/responsive-images.html
      var realViewportWidth,
          useLargeImages = false,
          firstResize = true,
          imageSrcWillChange;
 
      gallery.listen('beforeResize', function() {
 
        var dpiRatio = window.devicePixelRatio ? window.devicePixelRatio : 1;
        dpiRatio = Math.min(dpiRatio, 2.5);
        realViewportWidth = gallery.viewportSize.x * dpiRatio;
 
 
        if(realViewportWidth >= 1200 || (!gallery.likelyTouchDevice && realViewportWidth > 800) || screen.width > 1200 ) {
          if(!useLargeImages) {
            useLargeImages = true;
            imageSrcWillChange = true;
          }
 
        } else {
          if(useLargeImages) {
            useLargeImages = false;
            imageSrcWillChange = true;
          }
        }
 
        if(imageSrcWillChange && !firstResize) {
          gallery.invalidateCurrItems();
        }
 
        if(firstResize) {
          firstResize = false;
        }
 
        imageSrcWillChange = false;
 
      });
 
      gallery.listen('gettingData', function(index, item) {
        if( useLargeImages ) {
          item.src = item.o.src;
          item.w = item.o.w;
          item.h = item.o.h;
        } else {
          item.src = item.m.src;
          item.w = item.m.w;
          item.h = item.m.h;
        }
      });
 
      gallery.init();
    };
 
    // select all gallery elements
    var galleryElements = document.querySelectorAll( gallerySelector );
    for(var i = 0, l = galleryElements.length; i < l; i++) {
      galleryElements[i].setAttribute('data-pswp-uid', i+1);
      galleryElements[i].onclick = onThumbnailsClick;
    }
 
    // Parse URL and open gallery if it contains #&pid=3&gid=1
    var hashData = photoswipeParseHash();
    if(hashData.pid && hashData.gid) {
      openPhotoSwipe( hashData.pid,  galleryElements[ hashData.gid - 1 ], true, true );
    }
  };
 
  initPhotoSwipeFromDOM('.photoswipe_gallery');
})();

『data-med』なし

See the Pen 【JavaScript】スワイプができるlightbox系プラグイン『PhotoSwipe』のサンプル、『data-med』なしのバージョン by 125naroom (@125naroom) on CodePen.

HTMLとJavaScriptはこちら

HTML

<div class="ps_area_a photoswipe_gallery02">
  <figure>
    <a href="https://125naroom.com/wp/wp-content/uploads/2015/02/sora17.jpg" data-size="600x600"><img src="https://125naroom.com/wp/wp-content/uploads/2015/02/sora17.jpg" alt=""></a>
    <figcaption>sora 1</figcaption>
  </figure>
  <figure>
    <a href="https://125naroom.com/wp/wp-content/uploads/2015/02/sora16.jpg" data-size="600x600"><img src="https://125naroom.com/wp/wp-content/uploads/2015/02/sora16.jpg" alt=""></a>
    <figcaption>sora 2</figcaption>
  </figure>
  <figure>
    <a href="https://125naroom.com/wp/wp-content/uploads/2015/02/sora15.jpg" data-size="600x600"><img src="https://125naroom.com/wp/wp-content/uploads/2015/02/sora15.jpg" alt=""></a>
    <figcaption>sora 3</figcaption>
  </figure>
  <figure>
    <a href="https://125naroom.com/wp/wp-content/uploads/2015/02/sora10.jpg" data-size="600x600"><img src="https://125naroom.com/wp/wp-content/uploads/2015/02/sora10.jpg" alt=""></a>
    <figcaption>sora 4</figcaption>
  </figure>
  <figure>
    <a href="https://125naroom.com/wp/wp-content/uploads/2015/02/sora12.jpg" data-size="600x600"><img src="https://125naroom.com/wp/wp-content/uploads/2015/02/sora12.jpg" alt=""></a>
    <figcaption>sora 5</figcaption>
  </figure>
</div>
 
<!--モーダル用、置き場は自由ですが、フッター近くのほうがソースが綺麗かなと-->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="pswp__bg"></div>
  <div class="pswp__scroll-wrap">
    <div class="pswp__container">
      <div class="pswp__item"></div>
      <div class="pswp__item"></div>
      <div class="pswp__item"></div>
    </div>
    <div class="pswp__ui pswp__ui--hidden">
      <div class="pswp__top-bar">
        <div class="pswp__counter"></div>
        <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
        <button class="pswp__button pswp__button--share" title="Share"></button>
        <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
        <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
        <div class="pswp__preloader">
          <div class="pswp__preloader__icn">
            <div class="pswp__preloader__cut">
              <div class="pswp__preloader__donut"></div>
            </div>
          </div>
        </div>
      </div>
      <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
        <div class="pswp__share-tooltip"></div>
      </div>
      <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)"></button>
      <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)"></button>
      <div class="pswp__caption">
        <div class="pswp__caption__center"></div>
      </div>
    </div>
  </div>
</div>

JavaScript

// .photoswipe_gallery02
(function() {
  var initPhotoSwipeFromDOM = function(gallerySelector) {
 
    // parse slide data (url, title, size ...) from DOM elements 
    // (children of gallerySelector)
    var parseThumbnailElements = function(el) {
      var thumbElements = el.childNodes,
          numNodes = thumbElements.length,
          items = [],
          figureEl,
          linkEl,
          size,
          item;
 
      for(var i = 0; i < numNodes; i++) {
 
        figureEl = thumbElements[i]; // <figure> element
 
        // include only element nodes 
        if(figureEl.nodeType !== 1) {
          continue;
        }
 
        linkEl = figureEl.children[0]; // <a> element
 
        size = linkEl.getAttribute('data-size').split('x');
 
        // create slide object
        item = {
          src: linkEl.getAttribute('href'),
          w: parseInt(size[0], 10),
          h: parseInt(size[1], 10)
        };
 
 
 
        if(figureEl.children.length > 1) {
          // <figcaption> content
          item.title = figureEl.children[1].innerHTML; 
        }
 
        if(linkEl.children.length > 0) {
          // <img> thumbnail element, retrieving thumbnail url
          item.msrc = linkEl.children[0].getAttribute('src');
        } 
 
        item.el = figureEl; // save link to element for getThumbBoundsFn
        items.push(item);
      }
 
      return items;
    };
 
    // find nearest parent element
    var closest = function closest(el, fn) {
      return el && ( fn(el) ? el : closest(el.parentNode, fn) );
    };
 
    // triggers when user clicks on thumbnail
    var onThumbnailsClick = function(e) {
      e = e || window.event;
      e.preventDefault ? e.preventDefault() : e.returnValue = false;
 
      var eTarget = e.target || e.srcElement;
 
      // find root element of slide
      var clickedListItem = closest(eTarget, function(el) {
        return (el.tagName && el.tagName.toUpperCase() === 'FIGURE');
      });
 
      if(!clickedListItem) {
        return;
      }
 
      // find index of clicked item by looping through all child nodes
      // alternatively, you may define index via data- attribute
      var clickedGallery = clickedListItem.parentNode,
          childNodes = clickedListItem.parentNode.childNodes,
          numChildNodes = childNodes.length,
          nodeIndex = 0,
          index;
 
      for (var i = 0; i < numChildNodes; i++) {
        if(childNodes[i].nodeType !== 1) { 
          continue; 
        }
 
        if(childNodes[i] === clickedListItem) {
          index = nodeIndex;
          break;
        }
        nodeIndex++;
      }
 
 
 
      if(index >= 0) {
        // open PhotoSwipe if valid index found
        openPhotoSwipe( index, clickedGallery );
      }
      return false;
    };
 
    // parse picture index and gallery index from URL (#&pid=1&gid=2)
    var photoswipeParseHash = function() {
      var hash = window.location.hash.substring(1),
          params = {};
 
      if(hash.length < 5) {
        return params;
      }
 
      var vars = hash.split('&');
      for (var i = 0; i < vars.length; i++) {
        if(!vars[i]) {
          continue;
        }
        var pair = vars[i].split('=');  
        if(pair.length < 2) {
          continue;
        }           
        params[pair[0]] = pair[1];
      }
 
      if(params.gid) {
        params.gid = parseInt(params.gid, 10);
      }
 
      return params;
    };
 
    var openPhotoSwipe = function(index, galleryElement, disableAnimation, fromURL) {
      var pswpElement = document.querySelectorAll('.pswp')[0],
          gallery,
          options,
          items;
 
      items = parseThumbnailElements(galleryElement);
 
      // define options (if needed)
 
      options = {
 
        // define gallery index (for URL)
        galleryUID: galleryElement.getAttribute('data-pswp-uid'),
 
        getThumbBoundsFn: function(index) {
          // See Options -> getThumbBoundsFn section of documentation for more info
          var thumbnail = items[index].el.getElementsByTagName('img')[0], // find thumbnail
              pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
              rect = thumbnail.getBoundingClientRect(); 
 
          return {x:rect.left, y:rect.top + pageYScroll, w:rect.width};
        }
 
      };
 
      // PhotoSwipe opened from URL
      if(fromURL) {
        if(options.galleryPIDs) {
          // parse real index when custom PIDs are used 
          // http://photoswipe.com/documentation/faq.html#custom-pid-in-url
          for(var j = 0; j < items.length; j++) {
            if(items[j].pid == index) {
              options.index = j;
              break;
            }
          }
        } else {
          // in URL indexes start from 1
          options.index = parseInt(index, 10) - 1;
        }
      } else {
        options.index = parseInt(index, 10);
      }
 
      // exit if index not found
      if( isNaN(options.index) ) {
        return;
      }
 
      if(disableAnimation) {
        options.showAnimationDuration = 0;
      }
 
      // Pass data to PhotoSwipe and initialize it
      gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
      gallery.init();
    };
 
    // loop through all gallery elements and bind events
    var galleryElements = document.querySelectorAll( gallerySelector );
 
    for(var i = 0, l = galleryElements.length; i < l; i++) {
      galleryElements[i].setAttribute('data-pswp-uid', i+1);
      galleryElements[i].onclick = onThumbnailsClick;
    }
 
    // Parse URL and open gallery if it contains #&pid=3&gid=1
    var hashData = photoswipeParseHash();
    if(hashData.pid && hashData.gid) {
      openPhotoSwipe( hashData.pid ,  galleryElements[ hashData.gid - 1 ], true, true );
    }
  };
 
  // execute above function
  initPhotoSwipeFromDOM('.photoswipe_gallery02');
})();

『data-med』なし、『キャプション』なし

See the Pen 【JavaScript】スワイプができるlightbox系プラグイン『PhotoSwipe』のサンプル、『data-med』なし、『キャプション』なしのバージョン by 125naroom (@125naroom) on CodePen.

HTMLとJavaScriptはこちら

HTML

<div class="ps_area_a photoswipe_gallery02">
  <figure>
    <a href="https://125naroom.com/wp/wp-content/uploads/2015/02/sora17.jpg" data-size="600x600"><img src="https://125naroom.com/wp/wp-content/uploads/2015/02/sora17.jpg" alt="sora 1"></a>
  </figure>
  <figure>
    <a href="https://125naroom.com/wp/wp-content/uploads/2015/02/sora16.jpg" data-size="600x600"><img src="https://125naroom.com/wp/wp-content/uploads/2015/02/sora16.jpg" alt="sora 2"></a>
  </figure>
  <figure>
    <a href="https://125naroom.com/wp/wp-content/uploads/2015/02/sora15.jpg" data-size="600x600"><img src="https://125naroom.com/wp/wp-content/uploads/2015/02/sora15.jpg" alt="sora 3"></a>
  </figure>
  <figure>
    <a href="https://125naroom.com/wp/wp-content/uploads/2015/02/sora10.jpg" data-size="600x600"><img src="https://125naroom.com/wp/wp-content/uploads/2015/02/sora10.jpg" alt="sora 4"></a>
  </figure>
  <figure>
    <a href="https://125naroom.com/wp/wp-content/uploads/2015/02/sora12.jpg" data-size="600x600"><img src="https://125naroom.com/wp/wp-content/uploads/2015/02/sora12.jpg" alt="sora 5"></a>
  </figure>
</div>
 
<!--モーダル用、置き場は自由ですが、フッター近くのほうがソースが綺麗かなと-->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="pswp__bg"></div>
  <div class="pswp__scroll-wrap">
    <div class="pswp__container">
      <div class="pswp__item"></div>
      <div class="pswp__item"></div>
      <div class="pswp__item"></div>
    </div>
    <div class="pswp__ui pswp__ui--hidden">
      <div class="pswp__top-bar">
        <div class="pswp__counter"></div>
        <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
        <button class="pswp__button pswp__button--share" title="Share"></button>
        <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
        <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
        <div class="pswp__preloader">
          <div class="pswp__preloader__icn">
            <div class="pswp__preloader__cut">
              <div class="pswp__preloader__donut"></div>
            </div>
          </div>
        </div>
      </div>
      <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
        <div class="pswp__share-tooltip"></div>
      </div>
      <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)"></button>
      <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)"></button>
      <div class="pswp__caption">
        <div class="pswp__caption__center"></div>
      </div>
    </div>
  </div>
</div>

JavaScript

// .photoswipe_gallery02
(function() {
  var initPhotoSwipeFromDOM = function(gallerySelector) {
 
    // parse slide data (url, title, size ...) from DOM elements 
    // (children of gallerySelector)
    var parseThumbnailElements = function(el) {
      var thumbElements = el.childNodes,
          numNodes = thumbElements.length,
          items = [],
          figureEl,
          linkEl,
          size,
          item;
 
      for(var i = 0; i < numNodes; i++) {
 
        figureEl = thumbElements[i]; // <figure> element
 
        // include only element nodes 
        if(figureEl.nodeType !== 1) {
          continue;
        }
 
        linkEl = figureEl.children[0]; // <a> element
 
        size = linkEl.getAttribute('data-size').split('x');
 
        // create slide object
        item = {
          src: linkEl.getAttribute('href'),
          w: parseInt(size[0], 10),
          h: parseInt(size[1], 10)
        };
 
 
 
        if(figureEl.children.length > 1) {
          // <figcaption> content
          item.title = figureEl.children[1].innerHTML; 
        }
 
        if(linkEl.children.length > 0) {
          // <img> thumbnail element, retrieving thumbnail url
          item.msrc = linkEl.children[0].getAttribute('src');
        } 
 
        item.el = figureEl; // save link to element for getThumbBoundsFn
        items.push(item);
      }
 
      return items;
    };
 
    // find nearest parent element
    var closest = function closest(el, fn) {
      return el && ( fn(el) ? el : closest(el.parentNode, fn) );
    };
 
    // triggers when user clicks on thumbnail
    var onThumbnailsClick = function(e) {
      e = e || window.event;
      e.preventDefault ? e.preventDefault() : e.returnValue = false;
 
      var eTarget = e.target || e.srcElement;
 
      // find root element of slide
      var clickedListItem = closest(eTarget, function(el) {
        return (el.tagName && el.tagName.toUpperCase() === 'FIGURE');
      });
 
      if(!clickedListItem) {
        return;
      }
 
      // find index of clicked item by looping through all child nodes
      // alternatively, you may define index via data- attribute
      var clickedGallery = clickedListItem.parentNode,
          childNodes = clickedListItem.parentNode.childNodes,
          numChildNodes = childNodes.length,
          nodeIndex = 0,
          index;
 
      for (var i = 0; i < numChildNodes; i++) {
        if(childNodes[i].nodeType !== 1) { 
          continue; 
        }
 
        if(childNodes[i] === clickedListItem) {
          index = nodeIndex;
          break;
        }
        nodeIndex++;
      }
 
 
 
      if(index >= 0) {
        // open PhotoSwipe if valid index found
        openPhotoSwipe( index, clickedGallery );
      }
      return false;
    };
 
    // parse picture index and gallery index from URL (#&pid=1&gid=2)
    var photoswipeParseHash = function() {
      var hash = window.location.hash.substring(1),
          params = {};
 
      if(hash.length < 5) {
        return params;
      }
 
      var vars = hash.split('&');
      for (var i = 0; i < vars.length; i++) {
        if(!vars[i]) {
          continue;
        }
        var pair = vars[i].split('=');  
        if(pair.length < 2) {
          continue;
        }           
        params[pair[0]] = pair[1];
      }
 
      if(params.gid) {
        params.gid = parseInt(params.gid, 10);
      }
 
      return params;
    };
 
    var openPhotoSwipe = function(index, galleryElement, disableAnimation, fromURL) {
      var pswpElement = document.querySelectorAll('.pswp')[0],
          gallery,
          options,
          items;
 
      items = parseThumbnailElements(galleryElement);
 
      // define options (if needed)
 
      options = {
 
        // define gallery index (for URL)
        galleryUID: galleryElement.getAttribute('data-pswp-uid'),
 
        getThumbBoundsFn: function(index) {
          // See Options -> getThumbBoundsFn section of documentation for more info
          var thumbnail = items[index].el.getElementsByTagName('img')[0], // find thumbnail
              pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
              rect = thumbnail.getBoundingClientRect(); 
 
          return {x:rect.left, y:rect.top + pageYScroll, w:rect.width};
        }
 
      };
 
      // PhotoSwipe opened from URL
      if(fromURL) {
        if(options.galleryPIDs) {
          // parse real index when custom PIDs are used 
          // http://photoswipe.com/documentation/faq.html#custom-pid-in-url
          for(var j = 0; j < items.length; j++) {
            if(items[j].pid == index) {
              options.index = j;
              break;
            }
          }
        } else {
          // in URL indexes start from 1
          options.index = parseInt(index, 10) - 1;
        }
      } else {
        options.index = parseInt(index, 10);
      }
 
      // exit if index not found
      if( isNaN(options.index) ) {
        return;
      }
 
      if(disableAnimation) {
        options.showAnimationDuration = 0;
      }
 
      // Pass data to PhotoSwipe and initialize it
      gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
      gallery.init();
    };
 
    // loop through all gallery elements and bind events
    var galleryElements = document.querySelectorAll( gallerySelector );
 
    for(var i = 0, l = galleryElements.length; i < l; i++) {
      galleryElements[i].setAttribute('data-pswp-uid', i+1);
      galleryElements[i].onclick = onThumbnailsClick;
    }
 
    // Parse URL and open gallery if it contains #&pid=3&gid=1
    var hashData = photoswipeParseHash();
    if(hashData.pid && hashData.gid) {
      openPhotoSwipe( hashData.pid ,  galleryElements[ hashData.gid - 1 ], true, true );
    }
  };
 
  // execute above function
  initPhotoSwipeFromDOM('.photoswipe_gallery02');
})();

複数ギャラリーだって可能です

See the Pen 【JavaScript】スワイプができるlightbox系プラグイン『PhotoSwipe』のサンプル、複数ギャラリー by 125naroom (@125naroom) on CodePen.

HTMLとJavaScriptはこちら

HTML

<h3>ギャラリー01</h3>
 
<div class="ps_area photoswipe_gallery">
  <a href="https://125naroom.com/wp/wp-content/uploads/2015/02/sora17.jpg" data-size="600x600" data-med="https://125naroom.com/wp/wp-content/uploads/2015/02/sora17.jpg" data-med-size="600x600" data-author="125naroom">
    <img src="https://125naroom.com/wp/wp-content/uploads/2015/02/sora17.jpg" alt="">
    <figure>sora 1</figure>
  </a>
  <a href="https://125naroom.com/wp/wp-content/uploads/2015/02/sora16.jpg" data-size="600x600" data-med="https://125naroom.com/wp/wp-content/uploads/2015/02/sora16.jpg" data-med-size="600x600" data-author="125naroom">
    <img src="https://125naroom.com/wp/wp-content/uploads/2015/02/sora16.jpg" alt="">
    <figure>sora 2</figure>
  </a>
  <a href="https://125naroom.com/wp/wp-content/uploads/2015/02/sora15.jpg" data-size="600x600" data-med="https://125naroom.com/wp/wp-content/uploads/2015/02/sora15.jpg" data-med-size="600x600" data-author="125naroom">
    <img src="https://125naroom.com/wp/wp-content/uploads/2015/02/sora15.jpg" alt="">
    <figure>sora 3</figure>
  </a>
  <a href="https://125naroom.com/wp/wp-content/uploads/2015/02/sora10.jpg" data-size="600x600" data-med="https://125naroom.com/wp/wp-content/uploads/2015/02/sora10.jpg" data-med-size="600x600" data-author="125naroom">
    <img src="https://125naroom.com/wp/wp-content/uploads/2015/02/sora10.jpg" alt="">
    <figure>sora 4</figure>
  </a>
  <a href="https://125naroom.com/wp/wp-content/uploads/2015/02/sora12.jpg" data-size="600x600" data-med="https://125naroom.com/wp/wp-content/uploads/2015/02/sora12.jpg" data-med-size="600x600" data-author="125naroom">
    <img src="https://125naroom.com/wp/wp-content/uploads/2015/02/sora12.jpg" alt="">
    <figure>sora 5</figure>
  </a>
</div>
 
<h3>ギャラリー02</h3>
 
<div class="ps_area photoswipe_gallery">
  <a href="https://125naroom.com/wp/wp-content/uploads/2015/02/sora01.jpg" data-size="600x600" data-med="https://125naroom.com/wp/wp-content/uploads/2015/02/sora01.jpg" data-med-size="600x600" data-author="125naroom">
    <img src="https://125naroom.com/wp/wp-content/uploads/2015/02/sora01.jpg" alt="">
    <figure>sora 1</figure>
  </a>
  <a href="https://125naroom.com/wp/wp-content/uploads/2015/02/sora02.jpg" data-size="600x600" data-med="https://125naroom.com/wp/wp-content/uploads/2015/02/sora02.jpg" data-med-size="600x600" data-author="125naroom">
    <img src="https://125naroom.com/wp/wp-content/uploads/2015/02/sora02.jpg" alt="">
    <figure>sora 2</figure>
  </a>
  <a href="https://125naroom.com/wp/wp-content/uploads/2015/02/sora03.jpg" data-size="600x600" data-med="https://125naroom.com/wp/wp-content/uploads/2015/02/sora03.jpg" data-med-size="600x600" data-author="125naroom">
    <img src="https://125naroom.com/wp/wp-content/uploads/2015/02/sora03.jpg" alt="">
    <figure>sora 3</figure>
  </a>
  <a href="https://125naroom.com/wp/wp-content/uploads/2015/02/sora04.jpg" data-size="600x600" data-med="https://125naroom.com/wp/wp-content/uploads/2015/02/sora04.jpg" data-med-size="600x600" data-author="125naroom">
    <img src="https://125naroom.com/wp/wp-content/uploads/2015/02/sora04.jpg" alt="">
    <figure>sora 4</figure>
  </a>
  <a href="https://125naroom.com/wp/wp-content/uploads/2015/02/sora05.jpg" data-size="600x600" data-med="https://125naroom.com/wp/wp-content/uploads/2015/02/sora05.jpg" data-med-size="600x600" data-author="125naroom">
    <img src="https://125naroom.com/wp/wp-content/uploads/2015/02/sora05.jpg" alt="">
    <figure>sora 5</figure>
  </a>
</div>
 
<!--モーダル用、置き場は自由ですが、フッター近くのほうがソースが綺麗かなと-->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="pswp__bg"></div>
  <div class="pswp__scroll-wrap">
    <div class="pswp__container">
      <div class="pswp__item"></div>
      <div class="pswp__item"></div>
      <div class="pswp__item"></div>
    </div>
    <div class="pswp__ui pswp__ui--hidden">
      <div class="pswp__top-bar">
        <div class="pswp__counter"></div>
        <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
        <button class="pswp__button pswp__button--share" title="Share"></button>
        <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
        <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
        <div class="pswp__preloader">
          <div class="pswp__preloader__icn">
            <div class="pswp__preloader__cut">
              <div class="pswp__preloader__donut"></div>
            </div>
          </div>
        </div>
      </div>
      <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
        <div class="pswp__share-tooltip"></div>
      </div>
      <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)"></button>
      <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)"></button>
      <div class="pswp__caption">
        <div class="pswp__caption__center"></div>
      </div>
    </div>
  </div>
</div>

JavaScript

// .photoswipe_gallery
(function() {
  var initPhotoSwipeFromDOM = function(gallerySelector) {
 
    var parseThumbnailElements = function(el) {
      var thumbElements = el.childNodes,
          numNodes = thumbElements.length,
          items = [],
          el,
          childElements,
          thumbnailEl,
          size,
          item;
 
      for(var i = 0; i < numNodes; i++) {
        el = thumbElements[i];
 
        // include only element nodes 
        if(el.nodeType !== 1) {
          continue;
        }
 
        childElements = el.children;
 
        size = el.getAttribute('data-size').split('x');
 
        // create slide object
        item = {
          src: el.getAttribute('href'),
          w: parseInt(size[0], 10),
          h: parseInt(size[1], 10),
          author: el.getAttribute('data-author')
        };
 
        item.el = el; // save link to element for getThumbBoundsFn
 
        if(childElements.length > 0) {
          item.msrc = childElements[0].getAttribute('src'); // thumbnail url
          if(childElements.length > 1) {
            item.title = childElements[1].innerHTML; // caption (contents of figure)
          }
        }
 
 
        var mediumSrc = el.getAttribute('data-med');
        if(mediumSrc) {
          size = el.getAttribute('data-med-size').split('x');
          // "medium-sized" image
          item.m = {
            src: mediumSrc,
            w: parseInt(size[0], 10),
            h: parseInt(size[1], 10)
          };
        }
        // original image
        item.o = {
          src: item.src,
          w: item.w,
          h: item.h
        };
 
        items.push(item);
      }
 
      return items;
    };
 
    // find nearest parent element
    var closest = function closest(el, fn) {
      return el && ( fn(el) ? el : closest(el.parentNode, fn) );
    };
 
    var onThumbnailsClick = function(e) {
      e = e || window.event;
      e.preventDefault ? e.preventDefault() : e.returnValue = false;
 
      var eTarget = e.target || e.srcElement;
 
      var clickedListItem = closest(eTarget, function(el) {
        return el.tagName === 'A';
      });
 
      if(!clickedListItem) {
        return;
      }
 
      var clickedGallery = clickedListItem.parentNode;
 
      var childNodes = clickedListItem.parentNode.childNodes,
          numChildNodes = childNodes.length,
          nodeIndex = 0,
          index;
 
      for (var i = 0; i < numChildNodes; i++) {
        if(childNodes[i].nodeType !== 1) { 
          continue; 
        }
 
        if(childNodes[i] === clickedListItem) {
          index = nodeIndex;
          break;
        }
        nodeIndex++;
      }
 
      if(index >= 0) {
        openPhotoSwipe( index, clickedGallery );
      }
      return false;
    };
 
    var photoswipeParseHash = function() {
      var hash = window.location.hash.substring(1),
          params = {};
 
      if(hash.length < 5) { // pid=1
        return params;
      }
 
      var vars = hash.split('&');
      for (var i = 0; i < vars.length; i++) {
        if(!vars[i]) {
          continue;
        }
        var pair = vars[i].split('=');  
        if(pair.length < 2) {
          continue;
        }           
        params[pair[0]] = pair[1];
      }
 
      if(params.gid) {
        params.gid = parseInt(params.gid, 10);
      }
 
      return params;
    };
 
    var openPhotoSwipe = function(index, galleryElement, disableAnimation, fromURL) {
      var pswpElement = document.querySelectorAll('.pswp')[0],
          gallery,
          options,
          items;
 
      items = parseThumbnailElements(galleryElement);
 
      // define options (if needed)
      options = {
 
        //ここからオプション追加
        //          showHideOpacity: true,
        //          bgOpacity: 1,
        //          spacing: 0.12,
        //          maxSpreadZoom: 2,
        //          loop: true,
        //          pinchToClose: true,
        //          closeOnScroll: true,
        //          closeOnVerticalDrag: true,
        //          preload: [1,1],
        //ここまでオプション追加
 
        galleryUID: galleryElement.getAttribute('data-pswp-uid'),
 
        getThumbBoundsFn: function(index) {
          // See Options->getThumbBoundsFn section of docs for more info
          var thumbnail = items[index].el.children[0],
              pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
              rect = thumbnail.getBoundingClientRect(); 
 
          return {x:rect.left, y:rect.top + pageYScroll, w:rect.width};
        },
 
        addCaptionHTMLFn: function(item, captionEl, isFake) {
          if(!item.title) {
            captionEl.children[0].innerText = '';
            return false;
          }
          captionEl.children[0].innerHTML = item.title +  '<br/><small>Photo: ' + item.author + '</small>';
          return true;
        }
 
      };
 
 
      if(fromURL) {
        if(options.galleryPIDs) {
          // parse real index when custom PIDs are used 
          // http://photoswipe.com/documentation/faq.html#custom-pid-in-url
          for(var j = 0; j < items.length; j++) {
            if(items[j].pid == index) {
              options.index = j;
              break;
            }
          }
        } else {
          options.index = parseInt(index, 10) - 1;
        }
      } else {
        options.index = parseInt(index, 10);
      }
 
      // exit if index not found
      if( isNaN(options.index) ) {
        return;
      }
 
 
 
      if(disableAnimation) {
        options.showAnimationDuration = 0;
      }
 
      // Pass data to PhotoSwipe and initialize it
      gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
 
      // see: http://photoswipe.com/documentation/responsive-images.html
      var realViewportWidth,
          useLargeImages = false,
          firstResize = true,
          imageSrcWillChange;
 
      gallery.listen('beforeResize', function() {
 
        var dpiRatio = window.devicePixelRatio ? window.devicePixelRatio : 1;
        dpiRatio = Math.min(dpiRatio, 2.5);
        realViewportWidth = gallery.viewportSize.x * dpiRatio;
 
 
        if(realViewportWidth >= 1200 || (!gallery.likelyTouchDevice && realViewportWidth > 800) || screen.width > 1200 ) {
          if(!useLargeImages) {
            useLargeImages = true;
            imageSrcWillChange = true;
          }
 
        } else {
          if(useLargeImages) {
            useLargeImages = false;
            imageSrcWillChange = true;
          }
        }
 
        if(imageSrcWillChange && !firstResize) {
          gallery.invalidateCurrItems();
        }
 
        if(firstResize) {
          firstResize = false;
        }
 
        imageSrcWillChange = false;
 
      });
 
      gallery.listen('gettingData', function(index, item) {
        if( useLargeImages ) {
          item.src = item.o.src;
          item.w = item.o.w;
          item.h = item.o.h;
        } else {
          item.src = item.m.src;
          item.w = item.m.w;
          item.h = item.m.h;
        }
      });
 
      gallery.init();
    };
 
    // select all gallery elements
    var galleryElements = document.querySelectorAll( gallerySelector );
    for(var i = 0, l = galleryElements.length; i < l; i++) {
      galleryElements[i].setAttribute('data-pswp-uid', i+1);
      galleryElements[i].onclick = onThumbnailsClick;
    }
 
    // Parse URL and open gallery if it contains #&pid=3&gid=1
    var hashData = photoswipeParseHash();
    if(hashData.pid && hashData.gid) {
      openPhotoSwipe( hashData.pid,  galleryElements[ hashData.gid - 1 ], true, true );
    }
  };
 
  initPhotoSwipeFromDOM('.photoswipe_gallery');
})();

PhotoSwipeのダウンロード

まずはPhotoSwipeに必要なファイルをダウンロードします。

PhotoSwipeの使い方

ダウンロードファイルの中で必要なファイルは以下の4点です。
distフォルダに入っているかと思います。

  • photoswipe.css
  • default-skin.css
  • photoswipe.min.js
  • photoswipe-ui-default.min.js

HTML

<link rel="stylesheet" type="text/css" href="css/photoswipe.css">
<link rel="stylesheet" type="text/css" href="css/default-skin.css">
<script type="text/javascript" src="js/photoswipe.min.js"></script>
<script type="text/javascript" src="js/photoswipe-ui-default.min.js"></script>

CDNを使う場合は、

<link rel="stylesheet" type="text/css" href="css/photoswipe.css">
<link rel="stylesheet" type="text/css" href="css/default-skin.css">
<script type="text/javascript" src="js/photoswipe.min.js"></script>
<script type="text/javascript" src="js/photoswipe-ui-default.min.js"></script>

オプション設定

よく使うオプションをまとめました。

オプション説明初期値
showHideOpacity設定するとアニメーション化されます(画像の不透明度は常に1です)。false
bgOpacity背景(.pswp__bg)の不透明度。0から1までの数字である必要があります。この値はいくつかのジェスチャーベースのトランジションに使用されるため、このスタイルはCSSではなくJSによって定義されます。1
spacingスライドの間隔比。たとえば0.12、スライディングビューポート幅の12%としてレンダリングされます。false
maxSpreadZoomスプレッド(ズーム)ジェスチャを実行するときの最大ズームレベル。2は、画像を元のサイズから2倍に拡大できることを意味します。ここで大きな値を使用しないようにしてください。画像が大きすぎると、モバイル(特にiOS)でメモリの問題が発生する可能性があります。2
loopスワイプジェスチャーを使用するときにスライドをループします。設定すると、最後の画像から最初の画像にスワイプできます。true
pinchToCloseギャラリーのジェスチャーを閉じるためにピンチします。ユーザーがズームアウトすると、ギャラリーの背景は徐々にフェードアウトします。ジェスチャーが完了すると、ギャラリーが閉じます。true
closeOnScrollページスクロールでギャラリーを閉じます。オプションは、ハードウェアタッチサポートのないデバイスでのみ機能します。true
closeOnVerticalDrag垂直方向にドラッグするとき、および画像がズームされないときは、ギャラリーを閉じます。true
preload動きの方向に基づいて近くのスライドの遅延読み込み。最初の1つ-現在のイメージの前にプリロードするアイテムの数、2つ目-現在のイメージの後の2つの整数を持つ配列でなければなりません。たとえば、[1,3]に設定すると、現在の画像の前に1つの画像が読み込まれ、現在の画像の後に3つの画像が読み込まれます。値は1未満にはできません。[1,1]

下記ページにオプション内容と設定方法が詳細に載っています。英語ページですが日本語翻訳すれば問題ないかと思われます。

メモ

スマホ、タブレットで、スワイプができるlightbox系プラグイン『PhotoSwipe』の使い方と、制作に役立つ実装サンプルをまとめてみました。
正直なところ、jQueryではないので実装するのは少々面倒といいますか手間がかかるといいますか。。ですが、操作性、デザイン性、すべてにおいて素晴らしいので個人的にはとってもおすすめです。

PhotoSwipeのことで何かわからないことがあればPhotoSwipe公式サイトがあるので一度チェックしてみるといろいろ解決できたりしますよ。

さいごに

スワイプ、タッチ、ジェスチャー
スマホ、タブレットでの操作性が素晴らしいですー

関連記事

Author

デザコト

あ、いいな、と思うWebデザインを紹介しています。デザインの参考に。やさしいデザインが多いです。Webデザインギャラリー『デザインのこと - Web design gallery』を運営しています。

Googleさんの
おすすめ

11

/

21

2024

Googleさんの
おすすめ

11

/

21

2024

デザインの記事

水色デザイン
映画『アット・ザ・ベンチ』
【jQuery】スライダープラグイン「slick」実装サンプル集