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
conditional javascript execution based on browser window size?
提问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
, availHeight
and availWidth
attributes.
您可以使用screen
-object的height
,width
,availHeight
和availWidth
属性。
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 scroll
event callback.
您可以在scroll
事件回调中放置类似的内容。
If ($(window).width() < 1024) {
return;
}