JavaScript에서 미디어 쿼리를 사용하려면 코드는 다음과 같습니다. -
예시
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
color: white;
padding: 20px;
}
</style>
</head>
<body>
<h1>Using media queries with JavaScript Example</h1>
<h2>Resize the screen to see the color change from blue to red</h2>
<script>
var mediaQuery = window.matchMedia("(max-width: 700px)");
function setColor(mediaQuery) {
if (mediaQuery.matches) {
document.body.style.backgroundColor = "red";
} else {
document.body.style.backgroundColor = "blue";
}
}
setColor(mediaQuery);
mediaQuery.addListener(myFunction);
</script>
</body>
</html> 출력
위의 코드는 700px보다 큰 창 크기에서 다음 출력을 생성합니다 -

브라우저 창 크기를 700px 미만으로 조정할 때 -
