window.matchMedia method

window.matchMedia method returns a MediaQueryList object. window.matchMedia accepts media query strings as parameters.

const mql1 = window.matchMedia('(max-width: 600px)');

const mql2 = window.matchMedia('(min-width: 400px) and (max-width: 800px)');

MediaQueryList object

Attribute matches

Returns a boolean value. Determine whether the current document matches the media query string. The match returns true. Otherwise, it returns false.

const mql = window.matchMedia('(max-width: 600px)');

mql.matches

1.png

Does not match the media query string

2.png

Match media query string

Attribute media

Returns the media query string

const mql = window.matchMedia('(min-width: 400px) and (max-width: 800px)');

// "(min-width: 400px) and (max-width: 800px)"
mql.media

Method addListener

Add a listener for the MediaQueryList object.

const mql = window.matchMedia('(min-width: 400px) and (max-width: 800px)');

const callback = function () {
    if (mql.matches) {
        console.log('匹配')
    } else {
        console.log('不匹配')
    }
}

mql.addListener(callback)

Only when mql. When the matches changes, callback will be called. If you want to execute the logic from the beginning. You can call the callback manually

const mql = window.matchMedia('(min-width: 400px) and (max-width: 800px)');

const callback = function () {
    if (mql.matches) {
        console.log('匹配')
    } else {
        console.log('不匹配')
    }
}

callback()
mql.addListener(callback)

Method removeListener

Used to remove the listener

const mql = window.matchMedia('(min-width: 400px) and (max-width: 800px)');

const callback = function () {
    if (mql.matches) {
        console.log('匹配')
    } else {
        console.log('不匹配')
    }
}

mql.addListener(callback)
mql.removeListener(callback)

refer to


已注销
518 声望187 粉丝

想暴富