jQuery 窗口宽度 else if 语句

标签 jquery if-statement window width

我想知道为什么我的最后一个 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/

相关文章:

c - 强制使用 ANSI 编辑控件而不是 comctl32 编辑控件

javascript - 使用 slice() 后,检索包含该切片内某些内容的元素数

jquery - 为用户选项创建菜单

Javascript/NodeJs 优化重复的 if-else

Javascript 获取原始浏览器宽度或分辨率

javascript - window.onload延迟

javascript使用对象键和值的变量

javascript - 单击时获取 jQuery 上的 href 属性

python - 在 'if' 语句中设置多行条件的样式?

javascript - 使用数组填充 if 语句值