Skip to content

Instantly share code, notes, and snippets.

@manabuyasuda
Last active February 28, 2016 14:10
Show Gist options
  • Select an option

  • Save manabuyasuda/0b641887629fe436db72 to your computer and use it in GitHub Desktop.

Select an option

Save manabuyasuda/0b641887629fe436db72 to your computer and use it in GitHub Desktop.
ウィンドウサイズに応じて、src属性の'sp', 'pc'キーワードを切り替える
// @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);
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment