レスポンシブデザインでPC用の画像と、SP用の画像を変えるときに使うスクリプト。今回の案件では、bxsliderの画像(比率)をPCとSPで変えるため、PCとSPでボタンの画像を変更するために使いました。
1.
画像のフォルダに、PCとSP用の画像を用意しておきます。
PC用は「******_pc.jpg」のように「_pc」を画像のファイル名につける。
同様にSP用の画像には「_sp」を末尾に着ける。
2.
html を記述するときは、pc用の画像を参照するように書いておく。
3.
<img>タグには「switch」クラスを付与。
<li><a href="#"><img src="./common/images/sliderpic1_pc.png" class="switch"></a></li>
4.
PCとSPの共通のCSS(common.cssなど、、、)に以下の記述を追加する。
.switch{
visibility: hidden;
}
5.
以下のスクリプトを全ファイル共通のjsファイル、default.jsなど、、、に記述する。
"replace width= 767"の部分はメディアクエリーの切り替えサイズに合わせて書き換えてください。
// SPimage switch
$(function(){
var $setElem = $('.switch'),
pcName = '_pc',
spName = '_sp',
replaceWidth = 767;
$setElem.each(function(){
var $this = $(this);
function imgSize(){
var windowWidth = parseInt($(window).width());
if(windowWidth >= replaceWidth) {
$this.attr('src',$this.attr('src').replace(spName,pcName)).css({visibility:'visible'});
} else if(windowWidth < replaceWidth) {
$this.attr('src',$this.attr('src').replace(pcName,spName)).css({visibility:'visible'});
}
}
$(window).resize(function(){imgSize();});
imgSize();
});
});