2015-09-26 117 views
2

我有一点JS代码(由PHP回声),将放在我的网页的顶部。代码应该评估窗口大小,并基于此,转到移动版本或转到PC版本。js window.redirect不断更新

但是,当我loead我的网页(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>"; 
+0

你能提供围绕片段的上下文吗?在页面中特别是在什么点加载? – Romuloux

回答

1

我认为您应该将pc视图设置为默认值,并且仅当从移动设备打开视图时重定向。

这可以通过很多方式完成,但在我看来,this method是检测您提出请求的设备的最佳方式。

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

我从来没有考虑过这种方法!感谢您了解我这个! –

+1

@EVDEKSP我很高兴能帮助你:) – IlGala

2

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

因此,如果您加载主页,它会检查以查看您的屏幕大小。如果屏幕尺寸为主屏幕尺寸,则会将您重定向至主屏幕,然后重新开始。

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

未经测试示例如下:

$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插件都可以使移动侦测容易。 EG mobile-detect.js

+0

这工作!谢谢!我会看看插件! –