2013-10-17 35 views
1

我正在嘗試讓我的聯機幫助重定向到電話版本。不過,我從單一來源生成手機和臺式機版本,所以我想要一段代碼,可以在各個方面進行操作(電話< -769->桌面)。我得到了重定向由於使用尺寸發生:基於頁面標題/位置的重定向

if (screen.width <= 769 || windowWidth <= 769) { 
window.location = "../phone/Selecting_a_School_Register.htm"; 

,但是當我在電話頁面上它一直試圖加載的頁面(我可以看到爲什麼)。我了個去自己,但我是新來這個,這是我的(失敗)的嘗試:

windowWidth = window.innerWidth; 
<!-- 
if (location.pathname = "/desktop/Selecting_a_School_Register.htm";) 
{ 
} else if (screen.width <= 769 || windowWidth <= 769) { 
window.location = "../phone/Selecting_a_School_Register.htm"; 

} 
</script><script> 
if (location.pathname = "/phone/Selecting_a_School_Register.htm";) 
{ 
} else if (screen.width >= 769 || windowWidth >= 769) { 
window.location = "../desktop/Selecting_a_School_Register.htm"; 

} 
+0

移除Java標記 – SpringLearner

+0

一般來說你的web服務器應該是一個負責提供移動網頁。這是通過解析Http用戶代理來完成的。任何基於JavaScript的解決方案都將變得緩慢,維護困難,使用更多帶寬(由於額外的頁面加載),並且未來將難以維護,因爲它預計將在服務器端完成。根據您的緩存配置,它也可能無法正常工作。 – Deadron

回答

1

任何類型的條件語句都需要一個雙「==」,而不是一個單一的「=」喜歡你的代碼示例建議。另外,你的if語句中的字符串後面不需要分號。

即使比雙等於更好的是三重平等這是一個strict comparison operator

試試這個:

windowWidth = window.innerWidth; 

if (location.pathname === "/desktop/Selecting_a_School_Register.htm") { 
} 
else if (screen.width <= 769 || windowWidth <= 769) { 
    window.location = "../phone/Selecting_a_School_Register.htm"; 
} 

if (location.pathname === "/phone/Selecting_a_School_Register.htm") { 
} 
else if (screen.width >= 769 || windowWidth >= 769) { 
    window.location = "../desktop/Selecting_a_School_Register.htm"; 
} 

編輯:

此代碼不正是你所需要的:

var pathname = window.location.pathname 
    , width = window.innerWidth || document.documentElement.clientWidth || document.getElementsByTagName('body')[0].clientWidth; 

if (width <= 769 && pathname !== '/mobile.html') { 
    window.location = '/mobile.html'; 
} 

if (width > 769 && pathname !== '/desktop.html') { 
    window.location = '/desktop.html'; 
} 
+0

這有點改善了我的情況,但是,當我嘗試加載頁面時,它一直嘗試重新加載頁面,我認爲它忽略了第一個if語句或只是電話/桌面部分....任何想法? –

+0

@GeorgeWoodiwissHill看到我的編輯 – seanxe

0

嗨,

var isMobile = { 
    Android: function() { 
     return navigator.userAgent.match(/Android/i); 
    }, 
    BlackBerry: function() { 
     return navigator.userAgent.match(/BlackBerry/i); 
    }, 
    iOS: function() { 
     return navigator.userAgent.match(/iPhone|iPad|iPod/i); 
    }, 
    Opera: function() { 
     return navigator.userAgent.match(/Opera Mini/i); 
    }, 
    Windows: function() { 
     return navigator.userAgent.match(/IEMobile/i); 
    }, 
    any: function() { 
     return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows()); 
    } 
}; 

Example : 

To check to see if the user is on any of the supported mobile devices: 

if(isMobile.any()) alert('Mobile'); 

To check to see if the user is on a specific mobile device: 

if(isMobile.iOS()) alert('iOS'); 

謝謝 維沙爾帕特爾