1、問題:
用戶使用手機移動設備訪問127.0.0.1/yemian,自動識別到手機端並且跳轉至127.0.0.1/m/yemian
2、小二,上代碼:
//判斷是否是移動設備 var ua = navigator.userAgent; var UA = { Android:function () { //安卓 return ua.match(/Android/i)?true:false; }, BlackBerry:function() { //黑莓 return ua.match(/BlackBerry/i)?true:false; }, IOS:function(){ //IOS return ua.match(/iPhone|iPad|iPod/i)?true:false; }, //這個其實沒啥必要了,可以不用判斷這個,畢竟IE是一種古老的東西 Windows:function() { return ua.match(/IEMobile/i)?true:false; }, isMobile:function() { //移動設備 return UA.Android()||UA.BlackBerry()||UA.IOS()||UA.Windows(); } }
if(US.isMobile()){ //正則匹配第一個/,進行重定向 location.replace(location.href.replace(/\//,"/m/")); }
3、小二,這里為什么不使用location.href進行跳轉?
location.replace 不會保存跳轉前的URL地址,也就是不會把url放在history里,所以按返回之后會無效
使用區別:當要模擬按鈕點擊跳轉鏈接,使用location.href
如果只是單純進行http重定向,那就是用location.replace,作為csser,還是要考慮用戶體驗問題滴