Window
接口的
matchMedia()
method returns a new
MediaQueryList
object that can then be used to determine if the
document
matches the
media query
string, as well as to monitor the document to detect when it matches (or stops matching) that media query.
mqList = window.matchMedia(mediaQueryString)
mediaQueryString
MediaQueryList
.
新的
MediaQueryList
object for the media query. Use this object's properties and events to detect matches and to monitor for changes to those matches over time.
You can use the returned media query to perform both instantanteous and event-driven checks to see if the document matches the media query.
To perform a one-time, instantaneous check to see if the document matches the media query, look at the value of the
匹配
property, which will be
true
if the document meets the media query's requirements.
If you need to be kept aware of whether or not the document matches the media query at all times, you can instead watch for the
change
event to be delivered to the object. There's
a good example of this
in the article on
Window.devicePixelRatio
.
This example runs the media query
(max-width: 600px)
and displays the value of the resulting
MediaQueryList
's
匹配
property in a
<span>
; as a result, the output will say "true" if the viewport is less than or equal to 600 pixels wide, and will say "false" if the window is wider than that.
let mql = window.matchMedia('(max-width: 600px)');
document.querySelector(".mq-value").innerText = mql.matches;
The JavaScript code simply passes the media query to match into
matchMedia()
to compile it, then sets the
<span>
's
innerText
to the value of the results'
匹配
property, so that it indicates whether or not the document matches the media query at the moment the page was loaded.
<span class="mq-value"></span>
简单
<span>
to receive the output.
.mq-value {
font: 18px arial, sans-serif;
font-weight: bold;
color: #88f;
padding: 0.4em;
border: 1px solid #dde;
}
见 Testing media queries programmatically for additional code examples.
| 规范 | 状态 | 注释 |
|---|---|---|
|
CSSOM (CSS 对象模型) 视图模块
The definition of 'Window.matchMedia()' in that specification. |
工作草案 | 初始定义 |
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
matchMedia
|
Chrome 9 | Edge 12 | Firefox 6 | IE 10 | Opera 12.1 | Safari 5.1 | WebView Android ≤37 | Chrome Android 18 | Firefox Android 6 | Opera Android 12.1 | Safari iOS 5 | Samsung Internet Android 1.0 |
完整支持
Window
applicationCache
caches
closed
console
controllers
crossOriginIsolated
crypto
customElements
defaultStatus
devicePixelRatio
dialogArguments
目录
document
event
frameElement
frames
fullScreen
history
indexedDB
innerHeight
innerWidth
isSecureContext
isSecureContext
length
localStorage
location
locationbar
menubar
mozAnimationStartTime
mozInnerScreenX
mozInnerScreenY
mozPaintCount
名称
navigator
onabort
onafterprint
onanimationcancel
onanimationend
onanimationiteration
onappinstalled
onauxclick
onbeforeinstallprompt
onbeforeprint
onbeforeunload
onblur
oncancel
oncanplay
oncanplaythrough
onchange
onclick
onclose
oncontextmenu
oncuechange
ondblclick
ondevicelight
ondevicemotion
ondeviceorientation
ondeviceorientationabsolute
ondeviceproximity
ondragdrop
ondurationchange
onended
onerror
onfocus
onformdata
ongamepadconnected
ongamepaddisconnected
ongotpointercapture
onhashchange
oninput
oninvalid
onkeydown
onkeypress
onkeyup
onlanguagechange
onload
onloadeddata
onloadedmetadata
onloadend
onloadstart
onlostpointercapture
onmessage
onmessageerror
onmousedown
onmouseenter
onmouseleave
onmousemove
onmouseout
onmouseover
onmouseup
onmozbeforepaint
onpaint
onpause
onplay
onplaying
onpointercancel
onpointerdown
onpointerenter
onpointerleave
onpointermove
onpointerout
onpointerover
onpointerup
onpopstate
onrejectionhandled
onreset
onresize
onscroll
onselect
onselectionchange
onselectstart
onstorage
onsubmit
ontouchcancel
ontouchstart
ontransitioncancel
ontransitionend
onunhandledrejection
onunload
onuserproximity
onvrdisplayactivate
onvrdisplayblur
onvrdisplayconnect
onvrdisplaydeactivate
onvrdisplaydisconnect
onvrdisplayfocus
onvrdisplaypointerrestricted
onvrdisplaypointerunrestricted
onvrdisplaypresentchange
onwheel
opener
origin
outerHeight
outerWidth
pageXOffset
pageYOffset
parent
性能
personalbar
pkcs11
screen
screenLeft
screenTop
screenX
screenY
scrollbars
scrollMaxX
scrollMaxY
scrollX
scrollY
self
sessionStorage
sidebar
speechSynthesis
status
statusbar
toolbar
top
visualViewport
window
alert()
atob()
back()
blur()
btoa()
cancelAnimationFrame()
cancelIdleCallback()
captureEvents()
clearImmediate()
clearInterval()
clearTimeout()
close()
confirm()
convertPointFromNodeToPage()
convertPointFromPageToNode
createImageBitmap()
dump()
fetch()
find()
focus()
forward()
getAttention()
getComputedStyle()
getDefaultComputedStyle()
getSelection()
home()
matchMedia()
minimize()
moveBy()
moveTo()
open()
openDialog()
postMessage()
print()
prompt()
queueMicrotask()
releaseEvents()
requestAnimationFrame()
requestFileSystem()
requestIdleCallback()
resizeBy()
resizeTo()
restore()
routeEvent()
scroll()
scrollBy()
scrollByLines()
scrollByPages()
scrollTo()
setCursor()
setImmediate()
setInterval()
setTimeout()
showModalDialog()
sizeToContent()
stop()
updateCommands()
event
afterprint
animationcancel
animationend
animationiteration
beforeprint
beforeunload
blur
copy
cut
DOMContentLoaded
error
focus
hashchange
languagechange
load
message
messageerror
offline
online
orientationchange
pagehide
pageshow
paste
popstate
rejectionhandled
storage
transitioncancel
unhandledrejection
unload
vrdisplayconnect
vrdisplaydisconnect
vrdisplaypresentchange