首頁 >web前端 >js教程 >js判斷手機存取或PC的幾個例子(常用於手機跳轉)_javascript技巧

js判斷手機存取或PC的幾個例子(常用於手機跳轉)_javascript技巧

WBOY
WBOY原創
2016-05-16 15:25:321126瀏覽

例子一

<script>
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://www.jb51.net';
  }else{
 //window.location.href='http://m.jb51.net'; 
 }
}
$(function(){
 browserRedirect();
});
</script>

範例2

<script type="text/javascript">
(function(){
  var reWriteUrl = function(url){
    if(url){
      var Splits = url.split("/"),siteName=window.location.pathname;
      if(typeof siteName!=="undefined"){
        return "http://m.jb51.net"+siteName;
      }
    }
  };
  if(/Android|webOS|iPhone|iPad|Windows Phone|iPod|BlackBerry|SymbianOS|Nokia|Mobile/i.test(navigator.userAgent)){
    var url=window.location.href;
    var pathname=window.location.pathname;
    if(url.indexOf("&#63;mobile")<0){
    try{
      window.location.href=reWriteUrl(url);
    }catch(e){}
    }
  };
})();
</script>

注意,如果給搜尋引擎看的話我們在文件頭加入


意思是告訴搜尋引擎移動蜘蛛抓取的是手機版的.

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn