在JS中使用媒体查询
参考MDN
相关概念MediaQueryList
// 创建媒体查询列表对象
var mql = window.matchMedia("(orientation: portrait)");
// 添加监听器
mql.addListener(handleOrientationChange);
// 在当前状态下调用一次监听函数,更新当前媒体查询的结果,防止当前状态与开发者默认的状态不一致
handleOrientationChange(mql);
// 创建监听函数
function handleOrientationChange(mql) {
if (mql.matches) {
/* The viewport is currently in portrait orientation */
} else {
/* The viewport is currently in landscape orientation */
}
}
// 移除监听器
mql.removeListener(handleOrientationChange);
<spa style="float:left;"><div>
网友评论