通用组件做自适应

427 阅读1分钟

问题

做移动端,习惯使用 rem 。但有些业务类似的情况下,会希望抽离部分做成通用组件,比如弹窗、加载中、toast等。
但 rem 是通过设置 html 的 font-size 来起作用的,要迁移就不能设置这种全局的样式,以防污染。

解决

这不是个很好的方法,但对于小组件来说够了。

  1. 通过 scss 的 $mixin 传入一个参数,作为基数。 (其他扩展语言比如 less 都行,此处仅用scss 举例)
  2. 定义 @media 来设置不同屏幕下的基数,并传给定义好的 $mixin 即可。

优点

跟使用 rem 的效果没有任何区别。

缺点

会产生额外的 css , @media 分的越细重复的越多。
(但作为小组件而言,这点损耗还是可以接受的。)

示例

  $mixin mobile ($fontSize: $font){
    // .28 怎么来的呢,因为设计稿是 750 px,上面用的28 px
    font-size: $fontSize * .28 + px;
    padding: $fontSize * .16 + px  $fontSize * .4 + px;
    width: calc(100% - #{$fontSize * 1.2 + px});
  }
  @media only screen and (min-width: 800px) {
    $font:106.66666667;
    @include mobile($font);
  }
  @media only screen and (max-device-width: 414px), only screen and (min-width: 400px), only screen and (max-width: 800px){
    $font:55.2;
    @include mobile($font);
  }
  @media only screen and (max-device-width: 400px), only screen and (max-width: 400px) {
    $font:53.33333333;
    @include mobile($font);
  }
  @media only screen and (max-device-width: 375px), only screen and (max-width: 375px) {
    $font:50;
    @include mobile($font);
  }
  @media only screen and (max-device-width: 360px), only screen and (max-width: 360px) {
    $font:48;
    @include mobile($font);
  }
  @media only screen and (max-device-width: 320px), only screen and (max-width: 320px) {
    $font:42.66666667;
    @include mobile($font);
  }
  @media only screen and (max-device-width: 240px), only screen and (max-width: 240px) {
    $font:32;
    @include mobile($font);
  }