媒体查询

ffy Lv3

媒体查询入门指南
使用编程方法测试媒体查询

媒体查询入门

对于前端, 如果我们想实现响应式的设计, 那么媒体查询是必不可少的工具. 媒体查询可以帮助我们根据不同的设备和屏幕尺寸, 调整我们的网页的布局和样式.

媒体查询的范式:

1
2
3
@media media-type and (media-feature) {
/*css rules*/
}
  1. 媒体类型用于声明css文件被用作什么类型的媒体;
  2. 媒体表达式用于指定媒体特征, 只有满足媒体特征的条件下, 才会应用css规则;
  3. 通过测试且符合媒体类型的情况下应用内部的CSS样式.

media-type: all, print, screen, speech.

媒体特征

屏幕尺寸

使用min,max在一定的数值范围内启用当前的CSS样式.

如果去掉前缀, 将仅在恰好为当前数值中启用.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/* 启用宽度大于或等于600px的屏幕 */
@media screen and (max-width: 600px){
...
}

/* 启用宽度小于或等于600px的屏幕 */
@media screen and (min-width: 600px){
...
}

/* 窗口恰好等于600px时 */
@media screen and (width: 600px) {
...
}

朝向

orientation可以检测设备的方向, 如竖屏或横屏.

1
2
3
4
5
6
@media screen and (orientation: portrait) {
/* 竖放时的CSS样式 */
}
@media screen and (orientation: landscape) {
/* 横屏时的CSS样式 */
}

更复杂的媒体查询

  • and实现与逻辑:
1
2
3
4
5
@media screen and (min-width: 400px) and (orientation: landscape) {
body {
color: blue;
}
}
  • ,实现或逻辑:
1
2
3
4
5
@media (min-width: 768px) and (orientation: landscape), (max-width: 480px) {
/*
(屏幕宽度大于等于 768px 且屏幕方向为横向) 或 (屏幕宽度小于等于 480px)
*/
}

与C中的&|类似, 与的优先级更高, 先将and的条件进行判断, 然后视作整体.

  • not实现非逻辑:
1
2
3
@media not all and (orientation: landscape) {
/* 非全部屏幕且屏幕方向为横向 */
}
  • not实现 反转查询:

    与最近的and组合所绑定, 注意优先级

1
@media not screen and (color), print and (color) { ... }

,将媒体查询的表达式分为了前后两级, 因此上述的媒体查询等价于:

1
@media (not (screen and (color))), print and (color) { ... }

利用查询结果扩展设计

上述在CSS中利用@media可以实现响应式的设计, 如果我们希望在js/ts中使用媒体查询的结果呢? 利用媒体查询列表进行设计可以帮助我们实现更加自由的设计.

  • 使用window.matchMedia()方法存放媒体查询结果:
1
2
// 检测设备的旋转方向是否为纵向
var mediaQueryList = window.matchMedia("(orientation: portrait)");
  • 检查属性matches获取对应的查询结果:
1
2
3
4
5
if (mediaQueryList.matches) {
/* 设备的旋转方向为纵向 portrait */
} else {
/* 设备的旋转方向不是纵向,也就是横向 landscape */
}
  • 通过addListener()方法注册监听器, 持续监听查询列表的结果
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// 定义媒体查询字符串
const mediaQueryString: string = "(orientation: portrait)";

// 创建查询列表
const mediaQueryList: MediaQueryList = window.matchMedia(mediaQueryString);

// 定义回调函数,使用 MediaQueryListEvent 类型
function handleOrientationChange(event: MediaQueryListEvent): void {
if (event.matches) {
// 媒体查询匹配(竖屏)
console.log("Orientation changed to portrait");
// 在这里执行竖屏时的逻辑
} else {
// 媒体查询不匹配(横屏)
console.log("Orientation changed to landscape");
// 在这里执行横屏时的逻辑
}
}

// 先运行一次回调函数,传入 MediaQueryList 对象
handleOrientationChange({
matches: mediaQueryList.matches,
media: mediaQueryList.media,
type: 'change',
} as MediaQueryListEvent);

// 为查询列表注册监听器,同时将回调函数传给监听器
mediaQueryList.addEventListener('change', handleOrientationChange);

// (可选) 在组件卸载时或不再需要监听时,移除事件监听器
// mediaQueryList.removeEventListener('change', handleOrientationChange);
  • 标题: 媒体查询
  • 作者: ffy
  • 创建于 : 2025-01-08 19:16:49
  • 更新于 : 2025-05-09 17:31:21
  • 链接: https://ffy6511.github.io/2025/01/08/其他/媒体查询/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
评论