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
Does not match the media query string
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)
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。