最近では対応がほとんど必須となってきたPCでもスマートフォンでも閲覧できるように表示を切り分ける「レスポンシブ対応」。実装方法は様々ですが、今回はJavascriptでユーザーエージェントを取得したうえで、metaタグの追加やファイル名のリネーム等を行うためのjQueryをいくつかご紹介。
HTMLの例
03-5843-9329
jQueryの記述例
$(document).ready(function(){
/* ユーザーエージェント取得 */
var ua = navigator.userAgent.toLowerCase();
var isiPhone = (ua.indexOf('iphone') > -1);
var isAndroid = (ua.indexOf('android') > -1) && (ua.indexOf('mobile') > -1);
var isWindowsphone = (ua.indexOf('windows') > -1) && (ua.indexOf('phone') > -1);
/* スマホの場合の処理 */
if(isiPhone || isAndroid || isWindowsphone) {
/* 「head」内に「viewport」追加 */
$("head").append('');
/* 「style.css」を「style_sp.css」にリネームしてCSSを完全に切り分け */
$("link").each(function() {
var replace = $(this).attr('href').replace(/style.css/g,'style_sp.css');
$(this).attr('href',replace);
});
/* 「img」タグの画像パスを「img」から「img/sp」として画像格納フォルダを完全に切り分け */
$("img").each(function() {
var replace = $(this).attr('src').replace(/img/g,'img/sp');
$(this).attr('src',replace);
});
/* 「.tel」の中のテキストを取得してタップして電話がかけられるように変換、ハイフンも除去 */
$('.tel').each(function() {
var str = $(this).text();
$(this).html($('').attr('href', 'tel:' + str.replace(/-/g, '')).append(str + ''));
});
}
});








