14

我有一个滑出式导航栏,我希望在 >=1024 的屏幕宽度上默认打开并默认关闭 <1024。我有一个按钮可以切换它的打开和关闭。我刚开始学习js。如果窗口宽度> = 1024,我想有一种方法可以在 if 语句中设置默认切换状态。任何帮助将不胜感激。这是我到目前为止的切换。

$('a.expand').toggle(function() {
        $(this).addClass("open");
        $('#nav').animate({width: 50},{queue:false, duration:300});
        $('.wrapify').animate({marginLeft: 50},{queue:false, duration:300});
        $('.primarynav ul').hide();
        $('.navlogo').hide();   

  }, function() {
        $(this).removeClass("open");
        $('#nav').animate({width: 200},{queue:false, duration:300});
        $('.wrapify').animate({marginLeft: 200},{queue:false, duration:300});
        $('.primarynav ul').show();
        $('.navlogo').show(); 

  });
4

3 回答 3

33
$(document).ready(function() {
    // This will fire when document is ready:
    $(window).resize(function() {
        // This will fire each time the window is resized:
        if($(window).width() >= 1024) {
            // if larger or equal
            $('.element').show();
        } else {
            // if smaller
            $('.element').hide();
        }
    }).resize(); // This will simulate a resize to trigger the initial run.
});

编辑:

或者也许这就是你所追求的:

$(document).ready(function() {
    if($(window).width() >= 1024) {
        $('a.expand').click();
    }
});

如果宽度正确,这将在文档准备好时切换元素。

于 2011-09-13T17:22:07.530 回答
2

只需测试 screen.width > 1024.

https://developer.mozilla.org/en/DOM/window.screen.width

于 2011-09-13T16:43:04.377 回答
1

我正在做一个类似的项目,这段代码对我有用..

if($(window).width() >= 540) {
   //code to execute
}
于 2018-02-11T17:36:35.143 回答