Skip to content

imageSwitch.js

Manabu Yasuda edited this page Mar 4, 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';
  // ウィンドウサイズがreplaceWidth以上、もしくは未満の場合に処理が発生する。
  var replaceWidth = 768;

  $elem.each(function() {
    var $this = $(this);
    function imageSwitch() {
      var windowWidth = parseInt($(window).width());

      if(windowWidth >= replaceWidth) {
        $this.attr('src', $this.attr('src').replace(sp, pc));
      } else if(windowWidth < replaceWidth) {
        $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);
    });
  });
});

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

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

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

Clone this wiki locally