display:block/none;での画像切り替えではなく、画像のソースをjsで切り替えて表示する方法です。
スマホレイアウトになったときに、いちいち画像にクラス名を付与するのが面倒な場合便利です。
$(function () {
//変数セット
var $elem = $('.change');
var sp = '_sp.';
var pc = '_pc.';
var replaceWidth = 768;
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; //ミリSec
$(window).on('resize', function () {
clearTimeout(delayStart);
delayStart = setTimeout(function () {
imageSwitch();
}, delayTime);
});
});
切り替える画像は画像の名前の最後に、_pc、_spとつけるだけでOKです。







