jQuery Window Width else if statement

后端 未结 3 1889
天涯浪人
天涯浪人 2021-02-04 21:16

I am wondering why my last else if statement never gets executed. I am trying to do this:

$(document).ready(function() {
    function checkWidth() {
        var          


        
相关标签:
3条回答
  • 2021-02-04 21:49

    You are missing a couple >= in your code, and windowSize is not being compared but assigned a new value as a result of statements like windowSize = 480. Try this version instead:

    $(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);
    });​
    
    0 讨论(0)
  • 2021-02-04 22:00

    It's because of your else if statements. You're checking with a single equal sign, which is assigning the value.

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

    when you should be doing

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

    or >=, if that's the intended logic.

    0 讨论(0)
  • 2021-02-04 22:13

    You're missing a greater than sign :

    else if (windowSize = 720
    

    and using just the equal sign ?

    Try this instead:

    $(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

    0 讨论(0)
提交回复
热议问题