利用JavaScript实现PC端与移动端网页自动跳转

作者:闭包旅人时间:2026-10-30 05:25:30浏览:320

本文介绍如何通过JavaScript判断访问设备类型,实现PC端访问时自动跳转至移动端网页。通过检测User-Agent识别手机、平板等移动设备,并提供双向跳转代码示例,帮助开发者在不使用CSS自适应的情况下完成设备适配。

PC与移动端网页自动跳转方案

如果不希望使用CSS自适应来分别展示PC端和移动端的样式,可以通过JavaScript在检测到移动端访问PC端网页时,自动跳转到对应的移动端页面。以下方案经过测试,可直接使用。

1. 效果演示

PC端访问时的显示效果:

PC与移动端网页自动跳转方案

移动端访问时的显示效果:

PC与移动端网页自动跳转方案

JavaScript实现设备判断与跳转

2. 实现方法

若无需考虑移动端搜索引擎优化,只需通过JavaScript判断访问设备是否为移动端,并据此决定是否跳转至指定页面。核心JavaScript代码如下:


//判断是否移动端,如果是则跳转到指定的URL地址
function browserRedirect(url) {
//只读的字符串,声明了浏览器用于 HTTP 请求的用户代理头的值
var sUserAgent = navigator.userAgent.toLowerCase();
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 (bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) {
window.location.replace(url);
}
}

在页面中引入上述JavaScript文件,并调用相应方法即可实现跳转功能:


<script src="../js/wap.js"></script>
<script type="text/javascript">browserRedirect("http://ycdoit.com/test/testmobile.html");</script> 

提示:建议使用PC端和移动端设备分别访问演示页面,以验证跳转效果。

此外,以下提供几个常用的跳转代码片段:

PC端自动跳转至移动端

常用跳转代码示例


(function() {
      if (/Android|webOS|iPhone|iPad|Windows Phone|iPod|BlackBerry|SymbianOS|Nokia|Mobile|Opera Mini/i.test(navigator.userAgent)) {
        var siteName = window.location.pathname;
        if (url.indexOf("?pc") < 0) {
          try {
				if (typeof siteName !== "undefined") {
            	window.location.href = "https://m.jb51.net" + siteName
          		} 
          } catch (e) {}
        }
      }
    })();

移动端自动跳转至PC端


;(function() {
  var reWriteUrl = function(url) {
    if (url) {
      var Splits = url.split("/"),
      siteName = window.location.pathname;
      if (typeof siteName !== "undefined") {
        return "https://www.jb51.net" + siteName
      }
    }
  };
  if (!/Android|webOS|iPhone|iPad|Windows Phone|iPod|BlackBerry|SymbianOS|Nokia|Mobile|Opera Mini/i.test(navigator.userAgent)) {
    var url = window.location.href;
    var pathname = window.location.pathname;
    if (url.indexOf("?m") < 0) {
      try {
        window.location.href = reWriteUrl(url)
      } catch(e) {}
    }
  }
})();

以上就是基于JavaScript实现PC端访问时自动跳转至移动端网页的完整介绍,希望能对读者有所帮助。

作者最新文章