JS實現媒體查詢

項目中用到rem作單位,須要設置根元素html的fontSize,而且須要媒體查詢適配不一樣屏幕。
有個特殊需求,須要將項目嵌入其餘項目,而且此時去掉媒體查詢,獨立運行時仍然須要。所以不能直接用CSS寫媒體查詢,須要用JS控制添加。
CSS實現:html

@media screen and (max-width: 1280px) {
    html {
        font-size: 16px;
    }
}
@media screen and (max-width: 1366px) {
    html {
        font-size: 18px;
    }
}
@media screen and (max-width: 1580px) {
    html {
        /*開發/經常使用屏幕下設置爲20px,方便換算*/
        font-size: 20px; 
    }
}
@media screen and (min-width: 1581px) {
    html {
        font-size: 22px; 
    }
}

JS實現函數

// 建立查詢列表
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文檔matchMediacode

相關文章
相關標籤/搜索