Skip to content

imageSwitch.js

Manabu Yasuda edited this page Mar 28, 2016 · 6 revisions

スクリプト

  • $elemに置換対象にする要素を指定する
  • sppcに画像ファイルを置換するためのキーワードを指定する
  • replaceWidthに画像を切り替える分岐点を指定する
// @desc - img要素内のsrc属性をウィンドウサイズに応じて置換する。
// @example html
// <img src="image_sp.png" class="js-image-switch" alt="">
// CSSで画像の描画サイズを切り替えると、より柔軟に対応できる
// @see - https://gist.github.com/manabuyasuda/d000bcdcf5ea7ac17c9c
$(function() {
  // 置換の対象とするclass属性。
  var $elem = $('.js-image-switch');
  // 置換の対象とするsrc属性の末尾の文字列。
  var sp = '_sp.';
  var pc = '_pc.';
  // 画像を切り替えるウィンドウサイズ。
  var replaceWidth = 768;

  function imageSwitch() {
    // ウィンドウサイズを取得する。
    var windowWidth = parseInt(window.innerWidth);

    // ページ内にあるすべての`.js-image-switch`に適応される。
    $elem.each(function() {
      var $this = $(this);
      // ウィンドウサイズが768px以上であれば_spを_pcに置換する。
      if(windowWidth >= replaceWidth) {
        $this.attr('src', $this.attr('src').replace(sp, pc));

      // ウィンドウサイズが768px未満であれば_pcを_spに置換する。
      } else {
        $this.attr('src', $this.attr('src').replace(pc, sp));
      }
    });
  }
  imageSwitch();

  // 動的なリサイズは操作後0.2秒経ってから処理を実行する。
  var resizeTimer;
  $(window).on('resize', function() {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(function() {
      imageSwitch();
    }, 200);
  });
});

デフォルトでは.js-image-switchが指定されていて、_spが含まれている画像ファイルは768px以上になると_pcに置換される。_pcが含まれている画像ファイルは768px未満になると_spに置換される。

<!-- 768px未満 -->
<img src="image_sp.png" alt="" class="js-image-switch">

<!-- 768px以上 -->
<img src="image_pc.png" alt="" class="js-image-switch">

Clone this wiki locally