jQuery Window Width else if语句

时间:2012-08-23 01:19:34

标签: jquery if-statement window width

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

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

谢谢,

更新

对于任何有兴趣的人,我强烈推荐enquire.js插件:

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

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

3 个答案:

答案 0 :(得分:17)

您的代码中缺少一对&gt; = ,并且没有比较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);
});​

答案 1 :(得分:2)

你错过了一个大于号:

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);
});​

FIDDLE

答案 2 :(得分:2)

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

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

你应该做什么

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

或&gt; =,如果这是预期的逻辑。