• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Joanna Qian
Stay Hungry, Stay Foolish!
博客园    首页    新随笔    联系   管理    订阅  订阅
用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

posted on 2014-05-09 00:31  Joanna Qian  阅读(467)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3