让网页自动根据终端选择是移动版还是PC版?

    在移动设备应用越来越广泛的今天,许多网站都开始做移动端的界面展示,两者屏幕尺寸差异很大,所以展示的内容也有所差别。于是就遇到一个问题,如何判断你的页面是在移动端还是在PC端打开的呢?
    Navigator对象
    首先来了解一下Navigator 对象,Navigator 对象包含有关浏览器的信息,下面的userAgent 属性是一个只读的字符串,声明了浏览器用于 HTTP 请求的用户代理头的值。所以我们可以通过判断navigator.useragent里面是否有某些值来判断,比如我的电脑是mac,所以打印出来的值为Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
    看到里面含有 Mac 字样,其它类似。
那如何判断页面是在移动端还是PC端打开的呢?网上有很多方法,写的或难或简单,实际上一行代码就够了!
    window.location.href = /Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent) ? "https://www.baidu.com/" :  "http://news.baidu.com/";
    以上代码利用了正则表达式和三目运算符,含义就是如果是移动端打开的话那就跳转到 "https:www.baidu.com/" ,如果不是就跳转到"http://new.baidu.com/"。
 if(/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent))
  {
    window.location.href = "https://www.baidu.com/";
  }
 else
    {
      window.location.href = "http://news.baidu.com/";
    }
  window.location.href = /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|WebOS|Symbian|Windows Phone)/i.test(navigator.userAgent) ? "https://www.baidu.com/" : "http://news.baidu.com/";

让网页自动根据终端选择是移动版还是PC版?

上一篇:shiro多账号登录(用户名,手机号,邮箱)


下一篇:ASP.NET Core教程:ASP.NET Core使用AutoMapper