LoginSignup
0

More than 5 years have passed since last update.

スマホとPCのデバイスごとにhtmlファイルを切り分ける方法 ~『JavaScript』で条件分岐~

Last updated at Posted at 2018-02-27

この前、パソコンとスマートフォンで表示させるhtmlファイルを変えたかった時に調べたのでメモがてら。

以下のコードをパソコンでの閲覧時に表示させたいファイルのhead内に記述することで、デバイスごとに条件分岐させることができます。

<script type="text/javascript">
if ((navigator.userAgent.indexOf('iPhone') > 0 && navigator.userAgent.indexOf('iPad') == -1) || navigator.userAgent.indexOf('iPod') > 0 || navigator.userAgent.indexOf('Android') > 0) {
    // スマホ用のページにリダイレクトする
    location.href = '/sp/';
}
</script>

追記

このあと汎用CSSファイルが効かなくなったので別汎用ファイルを用意したのですが、何か理由があるのでしょうか、、

参考

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
0