js窗口.重定向不断更新

js window.redirect keeps updating

本文关键字:更新 重定向 窗口 js      更新时间:2023-09-26

我有一点JS代码(由PHP响应),将放在我的网页的顶部。代码应该评估窗口大小,并基于此,转到移动版本或转到pc版本。

但是当我加载我的页面(pc版本)时,页面一直刷新。我怎样才能停止休息?

代码如下:

$page = $_SERVER["PHP_SELF"];
        echo "<script>";
        echo "function screenSizeRedirect() 
            {
                var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
                var height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
                if (width <= 960) 
                {
                    window.location = 'http://m.bss21universe.ga$page';
                }
                if (width > 960)
                {
                    window.location = 'http://www.bss21universe.ga$page';
                }
            }";
    echo "screenSizeRedirect();";
    echo "</script>";

您正在重定向页面,即使您在正确的页面。

所以如果你加载主页,它会检查你的屏幕大小。如果屏幕尺寸为main,它会将您重定向到main,然后我们重新开始。

你需要写一张支票,以确保你没有重定向到你已经在的页面。

未测试样本如下:

$page = $_SERVER["PHP_SELF"];
    echo "<script>";
    echo "function screenSizeRedirect() 
        {
            var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
            var height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
            if (width <= 960  && window.location.href != 'http://m.bss21universe.ga$page') 
            {
                window.location = 'http://m.bss21universe.ga$page';
            }
            if (width > 960 && window.location.href != 'http://www.bss21universe.ga$page')
            {
                window.location = 'http://www.bss21universe.ga$page';
            }
        }";
echo "screenSizeRedirect();";
echo "</script>";

此外,还有比屏幕宽度更复杂的方法来检查移动设备,许多纯JS或jQuery插件可以使移动设备检测变得容易。如mobile-detect.js

我认为你应该将pc视图设置为默认值,并且只有在从移动设备打开视图时才重定向。

这可以通过多种方式实现,但在我看来,这种方法是检测发出请求的设备的最佳方法。

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
 window.location = 'http://m.bss21universe.ga$page';
}