javascript 基于浏览器窗口大小的条件javascript执行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12025666/
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-10-26 15:06:42  来源:igfitidea点击:

conditional javascript execution based on browser window size?

javascriptjquerycss

提问by nickpish

I have a simple jQuery function--detailed below-- that I'm using to manipulate the position of the document header, and I'm wondering if I can add a parameter such that the function is onlyexecuted if the browser window is of a certain size? In this case, I'd like the "stickyHeaderTop" function to execute only if the browser window width exceeds 1024px; is this possible?

我有一个简单的 jQuery 函数——详述如下——我用它来操纵文档标题的位置,我想知道是否可以添加一个参数,以便该函数在浏览器窗口为一定的尺寸?在这种情况下,我希望仅当浏览器窗口宽度超过 1024px 时才执行“stickyHeaderTop”函数;这可能吗?

<script type="text/javascript">
    $(function(){
    var stickyHeaderTop = $('header').offset().top;

    $(window).scroll(function(){
            if( $(window).scrollTop() > stickyHeaderTop ) {
                    $('header').css({position: 'fixed', top: '0px'});
            } else {
                    $('header').css({position: 'relative', top: '30px'});
            }
    });
});
</script>

回答by m90

You can use the screen-Object's height, width, availHeightand availWidthattributes.

您可以使用screen-object的heightwidthavailHeightavailWidth属性。

In case you want to execute some code on screens smaller than 800px for example just do:

如果你想在小于 800px 的屏幕上执行一些代码,例如:

if (screen.width < 800){
// do stuff
}

Be aware that this is an area that has some cross-browser pitfalls (and problems when having sth like the stumbleupon toolbar), so an alternative would be using jQuery (that you are already using) to detect your client's window size:

请注意,这是一个存在一些跨浏览器陷阱的区域(以及像 stumbleupon 工具栏一样的问题),因此另一种方法是使用 jQuery(您已经在使用)来检测客户端的窗口大小:

if ($(window).width() < 800){
// do stuff
}

Further reading at MDNregarding pure JS and jquery.comfor the jQuery part

MDN 上进一步阅读关于jQuery 部分的纯 JS 和jquery.com

回答by alex

You could place something like this in your scrollevent callback.

您可以在scroll事件回调中放置类似的内容。

If ($(window).width() < 1024) {
    return;
}