仿響應式html:JS來判斷頁面是在手機端還是在PC端打開的方法


版權聲明:本文為博主原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接和本聲明。
本文鏈接: https://blog.csdn.net/a419419/article/details/78752417

我們想要的效果是pc文件和mobile文件統一入口,適配不同的設備。
先看看項目的目錄:
這里寫圖片描述
在index.html里面配置js控制選擇那一個文件夾下的文件就可以了。
我們要利用:Navigator 對象,Navigator 對象包含有關瀏覽器的信息。
index.html很簡單,直接上碼吧:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no" />
		<script type="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://f.jcngame.com/fanfan20171208/mobile/index.html";
	            } else {
	                //跳轉pc端頁面
	                window.location.href="http://f.jcngame.com/fanfan20171208//fanmai/index.html";
	            }
	        }
			browserRedirect(); 
		</script>
	</head>
	<body>
		
	</body>
</html>
 

 

補充,感覺之前代碼太冗余了,現在用正則來優化了一下:

<script type="text/javascript">
	function browserRedirect() {
           var sUserAgent = navigator.userAgent.toLowerCase();
           if (/ipad|iphone|midp|rv:1.2.3.4|ucweb|android|windows ce|windows mobile/.test(sUserAgent)) {
               //跳轉移動端頁面
               window.location.href="http://f.jcngame.com/fanfan20171208/mobile/index.html";
           } else {
               //跳轉pc端頁面
               window.location.href="http://f.jcngame.com/fanfan20171208//fanmai/index.html";
           }
       }
	browserRedirect(); 
</script>
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM