有没有相当于使用@media查询的javascript?

时间:2015-07-20 07:34:12

标签: javascript html css

我有这段代码:

@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)动态添加或删除一个类来表示两个不同的大小,然后重新编码如下:

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

如果这样可行,那么有人可以评论是否使用Javascript是更好的方法吗?

1 个答案:

答案 0 :(得分:41)

您可以在javascript中使用window.matchMedia()进行媒体查询。

例如

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

请参阅以下链接以便更好地理解

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/"