本文介绍了利用JavaScript代码实现PC端与手机端网站自动跳转的具体方法。通过检测navigator.platform和userAgent属性,判断当前访问设备类型。在PC模板中嵌入代码,若为非PC设备则跳转至手机网址;在手机模板中嵌入代码,若为PC设备则跳转至PC网址。此外,还提供了基于URL关键词(如wap、3g)的二次判断逻辑,确保跳转准确性。
PC端模板中的设备检测与跳转代码
将以下JavaScript代码嵌入到PC端网页模板中,用于实现设备识别与跳转逻辑。
<script type="text/javascript">
//平台、设备和操作系统
var system ={
win : false,
mac : false,
xll : false
};
//检测平台
var p = navigator.platform;
system.win = p.indexOf("Win") == 0;
system.mac = p.indexOf("Mac") == 0;
system.x11 = (p == "X11") || (p.indexOf("Linux") == 0);
if(system.win||system.mac||system.xll){
}else{
window.location.href="手机网址";
}
</script>
手机端模板中的设备检测与跳转代码
将以下JavaScript代码嵌入到手机端网页模板中,用于实现设备识别与跳转逻辑。
<script type="text/javascript">
//平台、设备和操作系统
var system ={
win : false,
mac : false,
xll : false
};
//检测平台
var p = navigator.platform;
system.win = p.indexOf("Win") == 0;
system.mac = p.indexOf("Mac") == 0;
system.x11 = (p == "X11") || (p.indexOf("Linux") == 0);
if(system.win||system.mac||system.xll){
window.location.href="PC网址";
}else{
}
</script>
基于UserAgent和URL的跳转逻辑补充
补充说明:上述代码通过JS判断手机端和PC端,并执行相应的页面跳转操作。
var browser_class = navigator.userAgent;
var browser_class_name1 = browser_class.match("Mobile");
var browser_class_name2 = browser_class.match("mobile");
var location_url = window.location.href;
if (browser_class_name1 != null || browser_class_name2 != null){
if (location_url.match("wap") == null){
window.location.href="http://wap.xxxx.com";
}
} else
{
if (location_url.match("3g") != null || location_url.match("wap") != null){
window.location.href="http://wap.xxxx.com";
}
}
以上是基于JavaScript代码实现PC与手机之间跳转的完整介绍,供参考使用。