6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[ JavaScript ] ユーザーエージェントを判定し、<body>にクラスを付与する

Last updated at Posted at 2018-03-17

jQueryを使わず、JavaScriptのみで書いてみる版です。

スマートフォンの時は"sp"
 更にiPhoneの時は"iphone"、Androidの時は"android"

タブレットの時は"tablet"
 更にiPadの時は"ipad"、Androidの時は"android"

それ以外の時は"pc"
を付与します。

##Script

ua_addclass.js
window.onload = function () {
    var ua        = navigator.userAgent,
        bodyClass = document.body.classList;

    if (ua.indexOf('iPhone') > 0 || ua.indexOf('Android') > 0 && ua.indexOf('Mobile') > 0) {
        // スマートフォン
        bodyClass.add('sp');
        
        if(ua.indexOf('iPhone') > 0)  bodyClass.add('iphone');   // iPhone
        if(ua.indexOf('Android') > 0) bodyClass.add('android'); // Android

    } else if (ua.indexOf('iPad') > 0 || ua.indexOf('Android') > 0) {
        // タブレット
        bodyClass.add('tablet');

        if(ua.indexOf('iPad') > 0)    bodyClass.add('ipad');       // iPad
        if(ua.indexOf('Android') > 0) bodyClass.add('android'); // Android
    } else {
        // PC用コード
        bodyClass.add('pc');
    }
}// window.onload
6
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?