我想知道为什么我的最后一个 else 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 <= 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 之外,所有内容都会记录在控制台中。我做错了什么?
谢谢
更新:
对于仍然感兴趣的人,我强烈推荐 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);
});
关于jQuery 窗口宽度 else if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12083508/