ブログ

BLOG

CATEGORY

「レスポンシブ」aタグに入れた文字列を、パソコン表示、スマホ表示で、異なるURLに変更。

「ウインドウサイズに応じて、画像のファイル名を置換」するJSを元に、レスポンシブの、PC表示とSP表示で、それぞれ異なるリンク先を設定する。

規則性があるものと、規則性が無いものが混在するパターン。

  • $elem1、規則性有り。(単純にpcとspの文字列だけを置き換え)
  • $elem2、$elem3、規則性無し。(pcとspとで規則性が全く無いため、文字列は決め打ち。)

//link change
$(function() {
var $elem1 = $('.linkChange1');
var $elem2 = $('.linkChange2');
var $elem3 = $('.linkChange3');
var sp = '/sp';
var pc = '/pc';
var replaceWidth = 768;
function linkChange() {
var windowWidth = parseInt($(window).width());
$elem1.each(function() {
var $this = $(this);
if (windowWidth >= replaceWidth) {
$this.attr('href', $this.attr('href').replace(sp, pc));
} else {
$this.attr('href', $this.attr('href').replace(pc, sp));
}
});
$elem2.each(function() {
var $this = $(this);
if (windowWidth >= replaceWidth) {
$this.attr('href', $this.attr('href').replace('sp000102', 'pc000101'));
} else {
$this.attr('href', $this.attr('href').replace('pc000101', 'sp000102'));
}
});
$elem3.each(function() {
var $this = $(this);
if (windowWidth >= replaceWidth) {
$this.attr('href', $this.attr('href').replace('sp000201', 'pc000101'));
} else {
$this.attr('href', $this.attr('href').replace('pc000101', 'sp000201'));
}
});
}
linkChange();
var resizeTimer;
$(window).on('resize', function() {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(function() {
linkChange();
}, 200);
});
});

参考サイト、 jQueryでウィンドウサイズによって画像を切り替える