Javascript 如何检测响应式网页设计的屏幕尺寸?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31162606/
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
How to detect screen size for responsive web design?
提问by Zen-Lee Chai
I googled this and got a quirksmode sitethat gives you your screen size. Pulling up the console I see that screen.width
and screen.height
are directly available from the window object.
我用谷歌搜索了这个并得到了一个quirksmode 网站,它可以为您提供屏幕尺寸。拉起控制台我看到了,screen.width
并且screen.height
可以直接从 window 对象中获得。
I want to do the detection in pure JavaScript to get started. Can I use this property across all devices and browsers - mobile, tablet, PC and Chrome, Safari, IE, Firefox.
我想开始用纯 JavaScript 进行检测。我可以在所有设备和浏览器(手机、平板电脑、PC 和 Chrome、Safari、IE、Firefox)上使用此属性吗?
I don't care about the view port changing due to re-sizing etc. Just the actual size of the screen which does not change.
我不关心由于重新调整大小等导致的视口变化。只是屏幕的实际大小不会改变。
I was hoping there was a single property I could check across devices and browsers.
我希望有一个我可以跨设备和浏览器检查的属性。
Here is some general info by wikipedia on responsive web design.
这是维基百科关于响应式网页设计的一些一般信息。
采纳答案by Zen-Lee Chai
screen.width
is the property your are looking for.
screen.width
是您正在寻找的物业。
回答by l0w_skilled
Take a look at Get the device width in javascript
Media Queries work in js too:
媒体查询也适用于 js:
if (window.matchMedia('screen and (max-width: 768px)').matches) {}
Another way would be:
另一种方法是:
var width = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
回答by Karthik Sagar
This is what worked for me after long hunch. These attributes below provide responsive sizes based on new tab size.
经过长时间的预感,这对我有用。下面的这些属性提供基于新标签大小的响应大小。
window.innerWidth
window.innerHeight