jQueryで画像を切り替える
スマホ用画像とPC画像を、スマホ画像のサイズ(640px)を境に切り替えます。
スマホ用画像(画面幅は640px)
画像ファイルは、スマホ用の ”01_sp.png” が使用されています。
PC用画像(画面幅は641px)
画像ファイルは、PC用の ”01_pc.png” が使用されています。
ソース
<!DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>jQueryで画像を切り替える</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<style>
html,body {
margin: 0;
padding: 0;
}
header {
width: 100%;
height: 500px;
}
img {
max-width: 100%;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script>
$(function(){
var sizeChange = $('.switch'),//置換の対象とするclass属性
pcName = '_pc',//置換の対象とするsrc属性の末尾の文字列
spName = '_sp',//置換の対象とするsrc属性の末尾の文字列
replaceWidth = 640;//置換を切り替えるウィンドウサイズ
sizeChange.each(function(){
var $this = $(this);
function imgSize(){
//ウィンドウサイズが641以上ならspをpcに置換する
if(window.innerWidth > replaceWidth){
$this.attr('src',$this.attr('src').replace(spName,pcName));
} else {
$this.attr('src',$this.attr('src').replace(pcName,spName));
}
}
$(window).resize(function(){//横幅をリサイズした時に上でimgSize関数を有効にする
imgSize();
});
});
});
</script>
</head>
<body>
<header>
<img src="img/01_sp.png" alt="#" class="switch">
<!--01_sp.png 640x300-->
<!--01_pc.png 960x300-->
</header>
</body>
</html>