我正在尝试将我的在线帮助重定向到手机版本。但是,我从单一来源生成电话和桌面版本,因此我希望有一段代码可以分别执行此操作(电话 <-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";
}
最佳答案
任何类型的条件语句都需要两个“==”,而不是像代码示例所示的单个“=”。另外,您的 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';
}
关于javascript - 基于页面标题/位置的重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19424931/