「パソコン → スマホ」への切り替わりと「スマホ → パソコン」の切り替わりの両方を検知できる。
ブレイクポイントが2つ以上ある場合(= タブレット用の表示もある等)は対応していないので注意。
メリット・デメリット
- メリット
- js内に「ブレイクポイントの数値」を記載しなくて良いので、ブレイクポイントが変更になってもjsを変更する必要がない
(windownの幅で判定する場合はソース内にブレイクポイントを記述する必要があるので、ブレイクポイントが変更になるとソースも変更が必要) - デメリット
- 「PCで表示(shown-on-pc)」と「SPで表示(shown-on-sp)」のCSSがないとダメ、jsだけで完結しない
ソースコード
HTML
1 2 3 4 5 |
<h1 class="shown-on-pc">パソコン</h1> <h1 class="shown-on-sp">スマホ</h1> <p>※Chromeの「F12 → Console」でconsole.log()を確認できる</p> |
CSS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
.shown-on-pc { display: block; } .shown-on-sp { display: none; } h1 { color: black; font-size: 28px; text-align: center; padding: 20px 0; } p { font-size: 12px; text-align: center; } |
CSS(レスポンシブ)
1 2 3 4 5 6 7 8 9 10 11 |
@media(max-width: 750px) { .shown-on-pc { display: none; } .shown-on-sp { display: block; } } |
jQuery
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
$(function(){ function is_shown(name) { // "none"で判定することで、"block"や"inline-block"などは // 全て「表示中」だと判断できる if($(name).css('display') == 'none') { return false; } return true; } /* ブレイクポイント通過の瞬間を検知 「PC表示 = SP非表示」かつ「PC非表示 = SP表示」なので、 判定に用いるのは「PC表示(or 非表示)」だけで良い */ var shown_on_pc_last = is_shown('.shown-on-pc'); //初期化 $(window).on('resize', function() { // 現在の状態を取得 var shown_on_pc_now = is_shown('.shown-on-pc'); // ブレイクポイントを通過した瞬間を検知 // 現在と直前のフラグが一致しないときにブレイクポイントが切り替わったと判断できる if(shown_on_pc_now != shown_on_pc_last) { // 「SP -> PC」へ切り変わった瞬間 if(shown_on_pc_now) { console.log('SP -> PC'); } // 「PC -> SP」へ切り変わった瞬間 else { console.log('PC -> SP'); } } // 現在の状態を覚えておく shown_on_pc_last = shown_on_pc_now; }); }); |
コメントを残す