画像をレスポンシブに切り替え表示する方法

(posted at: 2016-02-22)

レスポンシブサイトの HTML/CSS マークアップの際によくある出来事。デザインとマークアップの役割分担が行われている場面では、特に覚悟しなければならない。

  1. ピクセル単位でグリッドがずれている
  2. illustrator でデザインした画像が photoshop に貼り付けられていてシェイプがぼけている
  3. PC 画面と SP 画面で別画像が使われている

当記事は、3番目の事象への対応方法の忘備録。

imgChange.js

上記サイトからソースをいただきました。

header の記述

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type='text/javascript' src="imgChange.js"></script>

javascript file

$(window).on('load resize', function(){

$(function(){
	var wid = $(window).width();
 
	if( wid < 480 ){ // window size
		$('.imgChange').each(function(){
			$(this).attr("src",$(this).data("img").replace('_pc', '_sp'));
		});
	}else {
		$('.imgChange').each(function(){
			$(this).attr("src",$(this).data("img"));
		});
	}
});
});

画像の記述例

<img src="" alt="ご予約・お問い合わせ" class="imgChange" data-img="contact_pc.png">

画像ファイル名を、PC 用は “xxx_pc” 、SP 用は “xxx_pc” としておけばよい。