我有一些JS代码(由PHP回应)将放在我的网页顶部。代码应评估窗口大小,并根据该大小,转到移动版本或转到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 :(得分:2)
您正在重定向页面,即使您在正确的页面上也是如此。
因此,如果您加载主页,则会检查您的屏幕大小。如果屏幕尺寸为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插件可用于使移动检测变得容易。 EG mobile-detect.js
答案 1 :(得分: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';
}