且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用jQuery在窗口调整大小上显示或隐藏元素

更新时间:2023-02-05 22:07:08

$(window).resize应该是正确的函数,但是您还需要调用该函数进行初始检查以确保菜单正确显示

$(window).resize should be the correct function but you also need to call the function to check initially to ensure the menu is shown correctly

//initialize the hamburger menu once on ready
$(document).ready(function() {
     var ham = $('.hamburger');

    //Hamburger Function
    ham.show();
    ham.click(function() {
        $('.menu').toggle();
    }); 

    //call the checkWindowWith by yourself on ready
    checkWindowWidth();
});

//register the resize function
$(window).resize(checkWindowWidth);

function checkWindowWidth() {
    var width = $(window).width();

    if (width <= 750) { 
        $('.hamburger').show();
        $('.nav').hide();          
    } else {
        $('.hamburger').hide();
        $('nav').show();
    }
}

jsfiddle演示