jquery if 语句基于屏幕大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7405213/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:48:48  来源:igfitidea点击:

jquery if statement based on screen size

jquerytogglescreen-size

提问by Drhodes

I have a slide out nav bar that I would like open by default on screen width of >=1024 and closed by default < 1024. I have a button that toggles it open and closed it. I'm just starting to learn js. I imagine there's a way to set a default toggle state in an if statement if the window width is >=1024. Any help would be greatly appreciated. Here's what I have so far for the toggle.

我有一个滑出式导航栏,我希望在 >=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(); 

  });

回答by demux

$(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.
});

Edit:

编辑:

Or maybe this is what you're after:

或者,这可能就是您所追求的:

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

This will toggle the element when document is ready if the width is correct.

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

回答by Blazemonger

回答by ArafPlays

I was doing a similar project and this code worked out for me..

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

if($(window).width() >= 540) {
   //code to execute
}