用JavaScript操作Media Queries

在响应式(或自适应)设计中要用到Media Queries这个CSS属性,但在某些时候我们需要对Media Queries进行动态操作,这时候可以使用Javascript。

如以下Media Queries的代码:

@media all and (max-width: 700px) {
    body {
        background: #FF0;
    }
}

我们可以使用javascript的window.matchMedia函数来操作Media Queries,该函数现在可以被大部分浏览器(包含IE9以上的版本)支持

var mq = window.matchMedia('@media all and (max-width: 700px)');
if(mq.matches) {
    // the width of browser is more then 700px
} else {
    // the width of browser is less then 700px
}
mq.addListener(function(changed) {
    if(changed.matches) {
        // the width of browser is more then 700px
    } else {
        // the width of browser is less then 700px
    }
});

参考: Using Media Queries in JavaScript

转载于:https://www.cnblogs.com/JoannaQ/p/3717979.html

猜你喜欢

转载自blog.csdn.net/weixin_33704591/article/details/93057329