判断当前的浏览器是pc还是移动设备,如果是手机,就跳转到对应手机端网站

判断当前的浏览器是pc还是移动设备,如果是手机,就跳转到对应手机端网站

    var sUserAgent=navigator.userAgent;

    var mobileAgents=['Android','iPhone','Symbian','WindowsPhone','iPod','BlackBerry','Windows CE'];

    var goUrl = 0;

    for( var i=0;i<mobileAgents.length;i++){

        if(sUserAgent.indexOf(mobileAgents[i]) > -1){

            goUrl = 1;

            break;

        }

    }

    if (goUrl == 1){

        location ='http://www.baidu.com';

    }

对应的手机站可以考虑wap.xxx.com; 或者3g.xxx.com;或者m.xxx.com等。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在 Nuxt.js ,我们可以使用插件判断PC 端还是移动端,然后根据不同的设备跳转到不同的路由。 下面的代码演示了如何编写一个插件来实现这个功能: ```javascript // plugins/device.js export default ({ app }, inject) => { const userAgent = process.server ? app.$ua.get('User-Agent') : navigator.userAgent const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test( userAgent ) inject('device', { isMobile, redirect(path) { const url = isMobile ? `/m${path}` : path if (process.client) { window.location.href = url } else { app.context.redirect(url) } } }) } ``` 在插件,我们首先获取了用户代理(userAgent),然后使用正则表达式来判断是否是移动设备。如果是移动设备,我们就将路径前缀设置为 "/m",否则就保持原样。 接着,我们定义了一个名为 "redirect" 的方法,用于根据设备类型跳转路由。如果在客户端调用该方法,我们就直接跳转到指定的 URL;如果在服务器端调用该方法,我们就使用上下文对象(context)的 redirect 方法来跳转路由。 最后,我们将插件作为 Nuxt.js 的插件进行注册: ```javascript // nuxt.config.js export default { plugins: ['~/plugins/device.js'] } ``` 现在,我们就可以在页面使用该插件了。例如,我们可以编写一个页面组件来测试: ```html <!-- pages/index.vue --> <template> <div> <h1>首页</h1> <button @click="goToAbout">跳转到关于页</button> </div> </template> <script> export default { methods: { goToAbout() { this.$device.redirect('/about') } } } </script> ``` 在上面的代码,我们定义了一个按钮,当用户点击该按钮时,就会调用 $device.redirect 方法来跳转到 "/about" 路由。如果是在移动设备上访问,就会跳转到 "/m/about" 路由。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小黑ii

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值