根据屏幕尺寸替换页面

Replace page based on screen size

我正在尝试根据屏幕尺寸重定向页面,我有两个不同的索引文件,一个用于网络的移动版本,第二个用于网络版本。

在我包含的网络版本索引文件中:

<script>
    if (screen.width <= 767) window.location.replace("./m/index.html")
        else window.location.replace("index.html")
</script>

我在移动索引页上添加了:

<script>
    if (screen.width >= 767) window.location.replace("../index.html")
        else window.location.replace("index.html")
</script>

问题是这些索引页面中有两个不断刷新,页面未加载。

这似乎是什么问题,感谢您的帮助。

你可以使用 resize javascript 事件,正如 Tushar 所说。

window.addEventListener("resize", getTemplate);

CurrentPage = 'DesktopPage';

function getTemplate() {
    if (screen.width >= 767 && CurrentPage != 'DesktopPage') {
        return window.location.replace("desktop.html");
    }

    if (screen.width < 767 && CurrentPage != 'MobilePage') {
        return window.location.replace("mobile.html");
    }
}

getTemplate();

这将检查您的当前页面和屏幕大小,因为如果您已经在桌面页面中,则重定向到桌面页面没有任何意义。


您还可以添加更多版本,例如 "SmallerMobilePage"。

window.addEventListener("resize", getTemplate);

CurrentPage = 'SmallerMobilePage';

function getTemplate() {
    if (screen.width >= 767 && CurrentPage != 'DesktopPage') {
        return window.location.replace("desktop.html");
    }

    if (screen.width < 767 && CurrentPage != 'MobilePage') {
        return window.location.replace("mobile.html");
    }

    if (screen.width <= 480 && CurrentPage != 'SmallerMobilePage') {
        return window.location.replace("smaller_mobile.html");
    }
}

getTemplate();