繁体   English   中英

JS-如果窗口高度小于___px,请执行某些操作-此代码有什么问题?

[英]JS - If window height is less than ___px, do something - What is wrong with this code?

如果用户的浏览器高度小于某个值,则尝试将用户发送到其他URL。 我希望它一直在进行检查,因此使用了setInterval函数。 我看不出有什么问题...

这是我正在使用的代码:

<script type="text/javascript">
        //if window height is less than 605px, go to google
    setInterval(function changeFont() {
    if (window.innerHeight < 605) {
    window.location = "http://google.com";

    }
    }, 1);
    </script>

在此之前,我运行以下代码,效果很好:

<script type="text/javascript">

    //if window is wider than 1340px, send to desktop
    setInterval(function sendToDesktop() {
    if (window.innerWidth >= 1340) {
    window.location = "../index.html";
    }
    }, 1);

    </script>

当我将代码用于屏幕高度时,即使屏幕高度低于605像素,重定向也无法正常工作。 有什么明显的我想念的地方吗?

问题是时间,您给了1.。平均值小于毫秒...您给了一个非常小的值。
因此,发生的事情是脚本执行得如此之快,以至于重定向不会发生。
我对此进行了测试,提供了10000的1,它起作用了! 因此,您必须更改1或使用下面显示的代码(它每次都会检查窗口高度)

<script> function setWindowHeight(){ var windowHeight = window.innerHeight; if (windowHeight < 605) { window.location = " http://google.com "; } } window.addEventListener("resize",setWindowHeight,false); </script>

在这里使用计时器真的是胡说八道。 只需定义一个检查窗口是否足够高并在调整大小时调用它的函数即可。 并且不要忘记在第一次加载时也调用它。

function checkHeightredirectToGoogle() {
  if (window.innerHeight < 605) {
    window.location = "https://google.com";
  }
}  

window.addEventListener("resize", function(){
  checkHeightredirectToGoogle()
}); 

checkHeightredirectToGoogle(); //first call

该解决方案将更易于编写和维护,并且在客户端计算机上也将更快,更不用说移动设备了,在这些设备上,改进甚至更高。

您正在执行的是强制浏览器每1ms排队一个函数。 当浏览器最终进入队列时,它会看到数百个函数在等待运行。 它运行功能- 所有这些功能最终都会评估为

window.location = 'http://google.com'

因此,您的浏览器会在几毫秒内进行几百次重定向。 在疯狂尝试时,更多功能正在排队。

查看您的代码,如果用户的屏幕为1440 x 600,问题将更加严重。两个重定向条件都将得到满足。

请在页面加载时检测并重定向,然后侦听任何后续的resize事件。

window.addEventListener('resize', detectAndRedirect);
function detectAndRedirect() {
    if (window.innerHeight < 605) {
        window.location = 'whatever url';
    }
    else if (window.innerWidth >= 1340) {
        window.location = 'whatever url';
    }
}

如果您确实必须使用计时器来检测分辨率,则更好的方法是:

var DETECT_PERIOD = 200;  // set something sensible.
setTimeout(detectAndRedirect, DETECT_PERIOD);

function detectAndRedirect() {
    if (window.innerHeight < 605) {
        window.location = 'whatever url';
    }
    else if (window.innerWidth >= 1340) {
        window.location = 'whatever url';
    }
    else {
        setTimeout(detectAndRedirect, DETECT_PERIOD);
    }
}

在这种情况下,您不认为1价值很小吗? 这些是毫秒。 这是第一件事,其次是:

我看不出有什么问题...

因此,如果您看不到任何错误,那么我们将如何帮助您? 您的确切问题是什么? 它不重定向? 控制台显示什么? 有什么错误吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM