xxxxxxxxxx
<html>
<head>
<meta charset="utf-8">
<title>高手教程(study.p2hp.com)</title>
</head>
<body>
<p>判断屏幕(screen/viewport)窗口大小,在小于等于 700 像素时修改背景颜色为黄色,大于 700 像素时修改背景颜色为粉红色。</p>
<p>重置浏览器大小查看效果。</p>
<script>
function myFunction(x) {
if (x.matches) { // 媒体查询
document.body.style.backgroundColor = "yellow";
} else {
document.body.style.backgroundColor = "pink";
}
}
var x = window.matchMedia("(max-width: 700px)")
myFunction(x) // 执行时调用的监听函数
x.addListener(myFunction) // 状态改变时添加监听器
</script>
</body>
</html>