LoginSignup
0
1

More than 1 year has passed since last update.

Lightboxのような画像リンクにwebpを対応させる方法

Posted at

webp対応したときに、Lightbox系の画像にaリンクが必要な実装をした場合、対応ブラウザの可否で .webp.png を書き換えなければいけなかったのでメモ。

前提:webp対応はModernizrを使用

ここでは前提として、JavaScriptライブラリ「Modernizr」を利用して、webpのブラウザ機能のサポート状況を自動的に検出してもらいます。

Modernizr

導入方法は割愛。(以下参考)

例:スライダーなどんお画像リストにaリンクのポップアップなどがある時

<ul class="gallery">
  <li>
    <a href="img/sample1.webp">
      <picture>
        <source srcset="img/sample1.webp" type="image/webp">
        <img src="img/sample1.png" alt="サンプル">
      </picture>
    </a>
  </li>
  <li>
    <a href="img/sample2.webp">
      <picture>
        <source srcset="img/sample2.webp" type="image/webp">
        <img src="img/sample2.png" alt="サンプル">
      </picture>
    </a>
  </li>
</ul>

Jsでhref属性をwebpとpngで切り替え

HTMLの画像をまとめて取得して、ループでhref属性の .webp.png に書き換えます。

$(function () {
    if ($('html').hasClass('no-webp')) {
        let link = document.querySelectorAll('.gallery > li > a');

        for (var i = 0; i < link.length; i++) {
            // console.log(link[i]);
            let oldHref = link[i].getAttribute('href');
            // console.log(oldHref);
            let newHref = oldHref.replace('.webp', '.png');
            // console.log(newHref);
            link[i].setAttribute('href', newHref);
        }
    }
});

こうすることで、webp対応ブラウザでは、.webp になり、非対応ブラウザでは .png のリンクになります。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1