基于页面标题/位置的重定向

时间:2013-10-17 11:03:45

标签: javascript redirect

我正在尝试将我的在线帮助重定向到手机版本。但是,我从单一来源生成手机和桌面版本,因此我希望有一段代码可以单独执行(电话< -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";

}

2 个答案:

答案 0 :(得分: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';
}

答案 1 :(得分: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');

谢谢, Vishal Patel