レスポンシブ イメージ スウィッチャー

最終更新日

画面幅に応じて読み込み画像のファイル名末尾「_pc」「_sp」を付け替えるやつ

$(function () {
	var $elem = $('.switch');
	var sp = '_sp.';
	var pc = '_pc.';
	var replaceWidth = 767; //break point
	function imageSwitch() {
		var windowWidth = parseInt($(window).width());
		$elem.each(function () {
			var $this = $(this);
			if (windowWidth >= replaceWidth) {
				$this.attr('src', $this.attr('src').replace(sp, pc));
			} else {
				$this.attr('src', $this.attr('src').replace(pc, sp));
			}
		});
	}
	imageSwitch();
	var delayStart;
	var delayTime = 200;
	$(window).on('resize', function () {
		clearTimeout(delayStart);
		delayStart = setTimeout(function () {
			imageSwitch();
		}, delayTime);
	});
});