JS判断访问设备是移动设备还是pc

<scripttype="text/javascript">
function browserRedirect() { 
var sUserAgent= navigator.userAgent.toLowerCase(); 
var bIsIpad= sUserAgent.match(/ipad/i) == "ipad"; 
var bIsIphoneOs= sUserAgent.match(/iphone os/i) == "iphone os"; 
var bIsMidp= sUserAgent.match(/midp/i) == "midp"; 
var bIsUc7= sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4"; 
var bIsUc= sUserAgent.match(/ucweb/i) == "ucweb"; 
var bIsAndroid= sUserAgent.match(/android/i) == "android"; 
var bIsCE= sUserAgent.match(/windows ce/i) == "windows ce"; 
var bIsWM= sUserAgent.match(/windows mobile/i) == "windows mobile"; 

if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) { 
window.location.href= 'http://url/mobile.html'; 
} else { 
window.location= 'http://url/pc.html'; 
} 
} 
browserRedirect(); 
</script>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 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
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值