菜单切换
FACESOHO知行者
心灵
记录
远方
赞赏工具
源代码:
点击运行
保存
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>小鸟启蒙(facesoho.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>
运行结果