3个方法实现JavaScript判断移动端及pc端访问不同的网站

  3个方法比较简单,分别在页面头部加入如下js代码:

  1. 对于简单地直接从www.maslinkcom跳转到m.maslink.com,此方法仅从首页而言:
<script>(function () {
var url = location.href;
// replace www.maslink.com with your domain
if ( (url.indexOf(‘www.maslink.com’) != -1) &&
navigator.userAgent.match(/(iPhone|iPod|Android|ios|iPad)/i) )
{location.href = ‘http://m.maslink.com';
}
})();
</script>

2.如果网站除了首页部分,后面跟的还有,比如:www.maslink.com/list/98/,对于这样一个url,PC就直接这样访问了, 对于移动端,只能需要通过m.maslink.com/list/98/才可以呈现出比较好的效果。把http://www替换为http://m,然后 更新页面就可以看到页面在移动端上呈现的效果了。

<script>
(function () {
var url = location.href;
// replace www.maslink.com with your domain
if ( (url.indexOf(‘www.maslink.com’) != -1) &&
navigator.userAgent.match(/(iPhone|iPod|Android|ios|iPad)/i) )
{var newUrl = url.replace(‘http://www’, ‘http://m’);
location.href = newUrl;
}
})();
</script>

3.还有一种方法是在用移动设备访问时给予提示:

<script>
var userAgentInfo = navigator.userAgent;
var Agents = new Array(“Android”, “iPhone”, “SymbianOS”, “Windows Phone”,
“iPad”, “iPod”);
var flag = false;
var v=0
for ( v = 0; v < Agents.length; v++)
{
if (userAgentInfo.indexOf(Agents[v]) > 0)
{ flag = true; break; }
}
if(flag){
window.location.href=”http://m.maslink.com”
alert(Agents[v]);// 设备类型
}
else
{
// pc
}
</script>

以上三种方法都是我在试验中验证了的,操作简单,效果明显,希望读者能用得上

转载于:https://www.cnblogs.com/webpush/p/4988500.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值