// 创建查询列表 let mql = [ window.matchMedia('(max-width: 1280px)'), window.matchMedia('(max-width: 1366px)'), window.matchMedia('(max-width: 1580px)') ] // 定义回调函数 function mediaMatchs () { let html = document.getElementsByTagName('html')[0] if (mql[0].matches) { html.style.fontSize = '16px' } else if (mql[1].matches) { html.style.fontSize = '18px' } else if (mql[2].matches) { html.style.fontSize = '20px' } else { html.style.fontSize = '22px' } } // 先运行一次回调函数 mediaMatchs() // 为查询列表注册监听器,同时将回调函数传给监听器 for (var i = 0; i < mql.length; i++) { mql[i].addListener(mediaMatchs) }
参考:MDN文档matchMedia