Skip to content

响应式

宽度

js获取宽度

js
//获取宽度
window.addEventListener('resize',()=>{
    console.log('resize', document.documentElement.clientWidth)
})

媒体查询

css
/* 默认展示红色 */
div {
  background-color: red;
}

/* 大于 640px 为 绿色 */
@media screen and (min-width: 640px) {
  div {
    background-color: green;
  }
}

/* 大于 768px 为蓝色 */
@media screen and (min-width: 768px) {
  div {
    background-color: blue;
  }
}

rem设置值

js
// 定义最大的 fontSize
const MAX_FONT_SIZE = 42

// 监听 html 文档被解析完成的事件
document.addEventListener('DOMContentLoaded', () => {

  // 获取 html 标签
  const html = document.querySelector('html')
  // 获取根元素 fontSize 标准,屏幕宽度 / 10
  let fontSize = window.innerWidth / 10
  // 获取到的 fontSize 不允许超过我们定义的最大值
  fontSize = Math.min(fontSize, MAX_FONT_SIZE)
  // 定义根元素(html)fontSize 的大小 (rem)
  html.style.fontSize = fontSize + 'px'

});

安全区域

需要设置viewport-fit=cover,同时设置 bottom: constant(safe-area-inset-bottom); bottom: env(safe-area-inset-bottom);

html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
  <title>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    .safe-area-bottom {
      position: fixed;
      bottom: constant(safe-area-inset-bottom);
      bottom: env(safe-area-inset-bottom);
      width: 100%;
      height: 46px;
      line-height: 46px;
      text-align: center;
      background-color: aqua;
    }
  </style>
</head>

<body>
  <div class="safe-area-bottom">
    下一步
  </div>
</body>

</html>