<div id="contents">
<h1>複数のメディアクエリをmatchMedia使って分岐してみよう!!</h1>
<h2>ブレイクポイント背景色が変わります。</h2>
<p id="result">現在はイベントが発生してません。</p>
<p>ブレイクポイントとするメディアクエリ:<span id="txt_media"></span>でイベント発生</p>
</div>
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
#contents {
padding: 20px;
}
h1{
margin-bottom:30px;
}
h2 {
margin-bottom: 20px;
}
p#result {
font-size: 18px;
font-weight: bold;
}
.bg_red {
background-color: #ff0000;
}
.bg_blue{
background-color: #0080FF;
}
.bg_yellow{
background-color: #F3F781;
}
function checkMediaQuery() {
$("#contents").removeClass();
if (window.matchMedia("(min-width:980px)").matches) {
//処理
$("#result").text("イベント発生しました");
$("#txt_media").text("min-width: 980px");
$("#contents").addClass("bg_yellow");
} else if (window.matchMedia("(min-width:769px)").matches) {
//処理
$("#result").text("イベント発生しました");
$("#txt_media").text("min-width: 769px");
$("#contents").addClass("bg_blue");
} else if (window.matchMedia("(min-width:481px)").matches) {
//処理
$("#result").text("イベント発生しました");
$("#txt_media").text("min-width: 481px");
$("#contents").addClass("bg_red");
}
}
//読み込み時とリサイズ時に関数を実行
window.onload = checkMediaQuery;
window.onresize = checkMediaQuery;
This Pen doesn't use any external CSS resources.