matchMedia 能否同时监听 min-width和max-width

看到网上很多文章都是只针对要么min-width,要么max-width来监听

var mql = window.matchMedia('(max-width: 760px)');
function screenTest(e) {
  if (e.matches) {
    document.body.style.backgroundColor = 'red';
  } else {
    document.body.style.backgroundColor = 'blue';
  }
}
mql.addListener(screenTest);

但是如果我这么写就不管用了

var mql = window.matchMedia('(min-width:380) and (max-width: 760px) ');
mql.addListener(screenTest);

请问怎样才能同时监听是否满足最大和最小值?

阅读 2.5k
1 个回答

根据 mdn 测试媒体查询 的说法应该是没有'(min-width: 380px) and (max-width: 760px)',这种写法的
你可以试试这样

window.matchMedia("(min-width: 380px)").matches &&
    window.matchMedia('(max-width: 760px)').matches
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题