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>
当我使用屏幕高度的代码时,重定向不起作用,即使屏幕高度低于605px。有什么明显的我遗漏了吗?
问题是时间,你给了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对一个函数进行排队。当浏览器最终到达队列时,它会看到几百个函数在等待运行。它运行函数-ALL,其中最终评估为
window.location = 'http://google.com'
因此,你的浏览器在几毫秒内进行了几百次重定向。当它疯狂地试图做到这一点时,更多的功能正在排队
看看你的代码,如果用户的屏幕是1440x600,问题会更严重。两个重定向条件都将得到满足。
请在页面加载时检测并重定向,然后侦听任何后续的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
在这种情况下值很小吗?这些是毫秒。这是第一件事,也是第二件事:
我看不出它出了什么问题…
所以,如果你看不出有什么问题,我们该如何帮助你呢?你的确切问题是什么?它不重定向?控制台显示什么?有错误吗?
- JavaScript代码问题:我正在将对象转换为数组
- 简单的Javascript代码问题
- 如果调试器关闭,Internet Explorer将出现运行代码问题
- AJAX自定义错误处理代码问题
- 花式盒子代码问题
- 谷歌分析事件跟踪代码问题
- 面临使用 javascript 的代码问题
- HTML页面头部出现Javascript代码问题
- JavaScript中的未来日期代码问题
- JavaScript代码问题
- js警报框中的资源文件变量给出字符串ASCII代码问题
- JQuery隐藏列表项超过5个代码问题
- AngularJS和JSON的代码问题
- Javascript代码问题"和& # 39;
- 验证代码问题
- 解析云代码问题中的条带模块
- SVG嵌入到HTML中,拖放代码问题
- 更新面板中的中继器- itemcommand代码问题-调用javascript函数与ScriptManager在代码后面
- Owl Carousel: Javascript不加载.Shopify问题或代码问题
- 从JSFiddle复制代码问题