4

我想知道为什么我的最后一个 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 中识别媒体查询的最佳方法。

4

3 回答 3

18

您的代码中缺少一对>=,并且 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);
});​
于 2012-08-23T01:23:54.267 回答
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);
});​

小提琴

于 2012-08-23T01:24:02.940 回答
2

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

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

当你应该做

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

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

于 2012-08-23T01:24:42.300 回答