jQuery Window Width else if语句

我想知道为什么我的最后一个if语句永远不会执行。 我想这样做:

$(document).ready(function() { function checkWidth() { var windowSize = $(window).width(); if (windowSize <= 479) { console.log("screen width is less than 480"); } else if (windowSize = 480 && windowSize <= 719) { console.log("screen width is less than 720 but greater than or equal to 480"); } else if (windowSize = 720 && windowSize = 960) { console.log("screen width is greater than or equal to 960"); } } // Execute on load checkWidth(); // Bind event listener $(window).resize(checkWidth); });​ 

除了最后一个if之外,所有内容都会在控制台中记录。 我究竟做错了什么?

谢谢,

更新:

对于仍然感兴趣的人,我强烈推荐enquire.js插件:

http://wicky.nillia.ms/enquire.js/

放下最好的方法我发现在JS中识别媒体查询。

您在代码中缺少一对> = ,并且没有比较windowSize,但是由于windowSize = 480类的语句而分配了一个新值。 请尝试使用此版本:

 $(document).ready(function() { function checkWidth() { var windowSize = $(window).width(); if (windowSize <= 479) { console.log("screen width is less than 480"); } else if (windowSize <= 719) { console.log("screen width is less than 720 but greater than or equal to 480"); } else if (windowSize <= 959) { console.log("screen width is less than 960 but greater than or equal to 720"); } else if (windowSize >= 960) { console.log("screen width is greater than or equal to 960"); } } // Execute on load checkWidth(); // Bind event listener $(window).resize(checkWidth); });​ 

你错过了一个大于号:

 else if (windowSize = 720 

并使用等号?

试试这个:

 $(document).ready(function() { function checkWidth() { var windowSize = $(window).width(); if (windowSize < 480) { console.log("screen width is less than 480"); } else if (windowSize < 720) { console.log("screen width is less than 720 but greater than or equal to 480"); } else if (windowSize < 960) { console.log("screen width is less than 960 but greater than or equal to 720"); } else { console.log("screen width is greater than or equal to 960"); } } // Execute on load checkWidth(); // Bind event listener $(window).resize(checkWidth); });​ 

小提琴

这是因为你的其他if语句。 您正在检查一个等号,即分配值。

 if ( windowSize = 480 && windowSize <= 719 ) 

什么时候你应该这样做

 if ( windowSize == 480 && windowSize <= 719 ) 

或> =,如果这是预期的逻辑。