是否有相当于使用@media 查询的 javascript?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31511001/
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
Is there a javascript equivalent to using @media query?
提问by Samantha J T Star
I have this code:
我有这个代码:
@media screen and (max-width: 570px) {
#header {
.flex-wrap(wrap);
.justify-content(center);
#headerTitles {
margin-top: 1rem;
}
}
}
@media screen and (min-width: 571px) and (max-width: 950px) {
#header.authenticated {
.flex-wrap(wrap);
.justify-content(center);
#headerTitles {
margin-top: 2rem;
}
}
}
Is there a way that I can use Javascript (not jQuery) to dynamically add or remove a class to the to represent the two different sizes and then recode this something like:
有没有一种方法可以使用Javascript(而不是jQuery)动态添加或删除一个类来表示两种不同的大小,然后重新编码如下:
.small #headerTitles { margin-top: 1rem; }
.large #headerTitles { margin-top: 2rem; }
If this works then can someone comment as to if using Javascript is a better way to do this?
如果这有效,那么有人可以评论使用 Javascript 是否是更好的方法吗?
回答by sahil gupta
You can use window.matchMedia()
for media queries in javascript.
您可以window.matchMedia()
在 javascript 中用于媒体查询。
for example
例如
var mq = window.matchMedia( "(max-width: 570px)" );
if (mq.matches) {
// window width is at less than 570px
}
else {
// window width is greater than 570px
}
Please refer the below links for better understanding
请参考以下链接以获得更好的理解
https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMediahttp://www.sitepoint.com/javascript-media-queries/
https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia http://www.sitepoint.com/javascript-media-queries/
Updated as per comment
根据评论更新
Please refer the plunker: "http://plnkr.co/edit/wAKFEFz0NU6ZaEmywlgc?p=preview"
请参考plunker:“ http://plnkr.co/edit/wAKFEFz0NU6ZaEmywlgc?p=preview”
For better understanding: "http://www.javascriptkit.com/javatutors/matchmediamultiple.shtml"
为了更好地理解:“ http://www.javascriptkit.com/javatutors/matchmediamultiple.shtml”
For web browser support information: "https://hacks.mozilla.org/2012/06/using-window-matchmedia-to-do-media-queries-in-javascript/"
有关 Web 浏览器支持信息:“ https://hacks.mozilla.org/2012/06/using-window-matchmedia-to-do-media-queries-in-javascript/”