jQuery Window Width else if语句 [英] jQuery Window Width else if statement
问题描述
我想知道为什么我的最后一个if语句永远不会被执行。我想这样做:
I am wondering why my last else if statement never gets executed. I am trying to do this:
$(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 <= 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);
});
一切都得到了在控制台中ogged除了最后的其他if。我做错了什么?
Everything gets logged in the console except for the last else if. What am I doing wrong?
谢谢,
更新:
对于仍然感兴趣的人,我强烈推荐enquire.js插件:
For anyone still interested, I highly recommend the enquire.js plugin:
http://wicky.nillia.ms/enquire.js/
放下最好的方法我发现在JS中识别媒体查询。
Hands down best approach I've found to recognizing media queries in JS.
推荐答案
你错过了一对> = 在你的代码中,并且没有比较windowSize,但是由于 windowSize = 480
等语句而分配了一个新值。请尝试使用此版本:
You are missing a couple >= in your code, and windowSize is not being compared but assigned a new value as a result of statements like windowSize = 480
. Try this version instead:
$(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);
});
这篇关于jQuery Window Width else if语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!