简体   繁体   English

获取窗口宽度javascript

[英]Get window width javascript

I am trying to measure the width of the current viewport to set variable thisWidth but getting 'undefined' 我试图测量当前视口的宽度来设置变量thisWidth但得到'undefined'

var thisWidth;
var browserWidth = $(window).width();

if(browserWidth > 590){
    var thisWidth= 180;
} else if(browserWidth > 350){
    var thisWidth= 150;
}

alert(thisWidth); // undefined??

Is there a better way to do this? 有一个更好的方法吗?

The reason I am doing it is to change a width variable(thisWidth) based on viewport width whether it be mobile or whatever. 我这样做的原因是根据视口宽度更改宽度变量(thisWidth),无论它是移动还是其他。

UPDATE - SOLVED Problem was, it was measuring before it had finished loading! 更新 - 已解决问题是,它是在完成加载之前测量的! Therefore coming in below 350 where finished width was 360 - weird actually 因此,在完成宽度为360的情况下进入350以下 - 实际上很奇怪

执行“jQuery ready”中的代码:

$(function(){ // Your code here })

The var s are redundant since they make variables local to the function scope . var是冗余的,因为它们使变量在函数范围内是局部的。 They don't hurt, but make the code less clear. 它们不会受到伤害,但会使代码不那么清晰。

I'm guessing you are missing a default value if browserWidth happens to be > 350 如果browserWidth恰好> 350我猜你错过了一个默认值

As others have pointed out, the extra var s are unnecessary and can be removed. 正如其他人所指出的那样,额外的var是不必要的,可以删除。 If you look at the logic, there's one case where thisWidth can be undefined after the if. 如果你看一下逻辑,有一种情况是在thisWidth可以不定义thisWidth What happens if browserWidth is less than or equal to 350? 如果browserWidth小于或等于350,会发生什么? Then neither of the assignments to thisWidth will run. 然后, thisWidth任何赋值thisWidth不会运行。 Add a final else to fix it. 添加最后一个修复它。

var thisWidth;
var browserWidth = $(window).width();

if(browserWidth > 590){
    thisWidth= 180;
} else if(browserWidth > 350){
    thisWidth= 150;
} else {
    thisWidth=42;
}

alert(thisWidth);

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

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