4

なぜ私の最後のelseifステートメントが実行されないのか疑問に思っています。私はこれをやろうとしています:

$(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でメディアクエリを認識するために私が見つけた最善のアプローチを伝えます。

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

それはあなたのelseifステートメントのせいです。値を割り当てている単一の等号でチェックしています。

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

あなたがしなければならないとき

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

または>=、それが意図されたロジックである場合。

于 2012-08-23T01:24:42.300 に答える