uni-app在H5与微信小程序下css不同单位显示对比

2022-08-15  本文已影响0人  科科Cole

平时经常会用到的css单位有px, rem, vw. 微信小程序中提供了rpx单位, uni-app会为我们在h5端将rpx自动转换为rem. 测试了一下模拟不同设备情况下的显示情况, 基准为375px的逻辑像素情况下, 16px = 1rem = 32rpx = 4.27vw. 先说结论:

uni-app中, 在h5环境下

uni-app中, 在微信小程序环境下


h5中, px固定大小很好解释; uni-app采用了类似flexible.js的解决方案, 会动态改变根html的font-size, 因此rem会动态缩放; rpx会被转为rem; vw会等比缩放也没什么好讲的.

微信小程序中, px固定大小没什么好说; rem也固定大小因为根font-size不会改变, 微信中提供了通过<page-meta>标签改变root-font-size的能力. 在微信里, 实际上rpx起了h5中rem的作用. 最后的vw会动态改变大小同h5.


截图:

H5 375px iPhone6
H5 414px iPhone XR
H5 390px iPhone 12/13(Pro)
H5 820px iPad Air
微信小程序 375px iPhone6
微信小程序 320px iPhone5
微信小程序 414px iPhone XR
微信小程序 390px iPhone 12/13(Pro)
微信小程序 834px iPad Pro 10.5-inch

垃圾代码:

<template>
  <view class="absolute left-3 top-3">deviceWidth: {{ deviceWidth }}px</view>
  <view class="h-screen flex flex-col justify-center items-center gap-5">
    <view class="flex">
      <view class="w-[50px] bg-yellow">16px</view>
      <view id="a" style="width: 16px; height: 16px" class="bg-black"></view>
      <view class="m-l-3 w-50">{{ as }}</view>
    </view>
    <view class="flex">
      <view class="w-[50px] bg-yellow">1rem</view>
      <view id="b" style="width: 1rem; height: 1rem" class="bg-black"></view>
      <view class="m-l-3 w-50">{{ bs }}</view>
    </view>
    <view class="flex">
      <view class="w-[50px] bg-yellow">32rpx</view>
      <view id="c" style="width: 32rpx; height: 32rpx" class="bg-black"></view>
      <view class="m-l-3 w-50">{{ cs }}</view>
    </view>
    <view class="flex">
      <view class="w-[50px] bg-yellow">4.27vw</view>
      <view id="d" style="width: 4.27vw; height: 4.27vw" class="bg-black"></view>
      <view class="m-l-3 w-50">{{ ds }}</view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { useNodeSelector } from "@/composables/useNodeSelector";
import { onReady } from "@dcloudio/uni-app";
import { getCurrentInstance } from "vue";

const deviceWidth = uni.getSystemInfoSync().windowWidth;

const instance = getCurrentInstance();
const { info: infoa, update: updatea } = $(useNodeSelector("#a", { instance, size: true }));
const { info: infob, update: updateb } = $(useNodeSelector("#b", { instance, size: true }));
const { info: infoc, update: updatec } = $(useNodeSelector("#c", { instance, size: true }));
const { info: infod, update: updated } = $(useNodeSelector("#d", { instance, size: true }));

let as = $computed(() => `${infoa?.width}px * ${infoa?.height}px`);
let bs = $computed(() => `${infob?.width}px * ${infob?.height}px`);
let cs = $computed(() => `${infoc?.width}px * ${infoc?.height}px`);
let ds = $computed(() => `${infod?.width}px * ${infod?.height}px`);

onReady(() => {
  updatea();
  updateb();
  updatec();
  updated();
});
</script>
上一篇 下一篇

猜你喜欢

热点阅读