使用device.js检测设备并实现不同设备展示不同网页


现在很多时候会用@media来控制页面在不同分辨率的设备商展示不同效果,但是有些时候想在直接在PC上展示一个做好的页面,在mobile展示另一个页面。这个时候可以借助device.js来检测设备,然后打开不同的页面(device.js 是一个可以用来检测设备,操作系统和方向的js库)。当然这种做法需要一次跳转。


假设有个m.html想用于mobile端展示,pc.html想用于pc端展示。这个时候可以用index.html作为入口,在<head>内引入device.js来检测设备,然后用js来实现跳转。

当设备为Mobile和tablet的时候展示m.html

否则展示pc.html


实现代码如下

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>responsive demo</title>
  <script src="device.js"></script>
</head>

<body style="margin: auto; position: absolute; width:100%; height: 100%">

<script>
 var isMobile = device.mobile(),
            isTable = device.tablet();

    if(isMobile || isTable){
        window.open("m.html","_self");
    }
    else{
         window.open("pc.html","_self");
    }
</script>
</body>
</html>

其中device.js代码如下

(function() {
  var previousDevice, _addClass, _doc_element, _find, _handleOrientation, _hasClass, _orientation_event, _removeClass, _supports_orientation, _user_agent;

  previousDevice = window.device;

  window.device = {};

  _doc_element = window.document.documentElement;

  _user_agent = window.navigator.userAgent.toLowerCase();

  device.ios = function() {
    return device.iphone() || device.ipod() || device.ipad();
  };

  device.iphone = function() {
    return _find('iphone');
  };

  device.ipod = function() {
    return _find('ipod');
  };

  device.ipad = function() {
    return _find('ipad');
  };

  device.android = function() {
    return _find('android');
  };

  device.androidPhone = function() {
    return device.android() && _find('mobile');
  };

  device.androidTablet = function() {
    return device.android() && !_find('mobile');
  };

  device.blackberry = function() {
    return _find('blackberry') || _find('bb10') || _find('rim');
  };

  device.blackberryPhone = function() {
    return device.blackberry() && !_find('tablet');
  };

  device.blackberryTablet = function() {
    return device.blackberry() && _find('tablet');
  };

  device.windows = function() {
    return _find('windows');
  };

  device
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值