是否有JavaScript等效于使用@media查询? [英] Is there a javascript equivalent to using @media query?

查看:169
本文介绍了是否有JavaScript等效于使用@media查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码:

@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;
        }
    }

}

我可以使用Javascript(不是jQuery)动态添加或删除一个类来表示两种不同的大小,然后重新编码这样的东西:

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:

.small #headerTitles { margin-top: 1rem; }
.large #headerTitles { margin-top: 2rem; }

如果这个工作,那么有人可以评论如果使用Javascript是更好的方法吗?

If this works then can someone comment as to if using Javascript is a better way to do this?

推荐答案

您可以使用 / API / Window / matchMediarel =nofollow> window.matchMedia()

You can use window.matchMedia() for media queries in javascript.

例如

var mq = window.matchMedia( "(max-width: 570px)" );
if (mq.matches) {
    // window width is at less than 500px
}
else {
    // window width is greater than 500px
}

请参阅以下链接了解理解

Please refer the below links for beeter understanding

https://developer.mozilla.org/en -US / docs / Web / API / Window / matchMedia
http: //www.sitepoint.com/javascript-media-queries/

根据注解更新

请参阅plunker http://plnkr.co/edit / wAKFEFz0NU6ZaEmywlgc?p = preview

为了更好地理解 http://www.javascriptkit.com/javatutors/matchmediamultiple.shtml

对于网络浏览器支持信息
https:// hacks.mozilla.org/2012/06/using-window-matchmedia-to-do-media-queries-in-javascript/

For web Browser Support Info "https://hacks.mozilla.org/2012/06/using-window-matchmedia-to-do-media-queries-in-javascript/"

这篇关于是否有JavaScript等效于使用@media查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆