博客 / 詳情

返回

在 Vue 3 項目配置 rem

在 Vue 3 中配置 rem 時,設計稿1920,如果你希望實現一個最小寬度為 1024px 的適配,意思是當屏幕寬度小於 1024px 時不再縮小字體大小,始終保持最小寬度的 rem 配置。可以通過動態設置根元素的字體大小來實現。

一、安裝插件

pnpm install amfe-flexible --save

二、自定義方法

根目錄新建 utils/rem.js文件

(function () {
  const baseWidth = 1920; // 設計稿寬度
  const baseFontSize = 16; // 根字體大小(1rem = 16px)
  const docEl = document.documentElement;

  const resize = () => {
    const clientWidth = Math.max(docEl.clientWidth, 1024); // 設置最小寬度限制
    const scale = clientWidth / baseWidth;
    console.log(baseFontSize * scale, "字體大小");
    let fontSize = baseFontSize * scale;
    if (fontSize < 12) {
      fontSize = 12;
    }
    docEl.style.fontSize = fontSize + "px";
  };

  resize();
  window.addEventListener("resize", resize);
})();

三、main.ts引入

import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import "amfe-flexible";
import "./utils/rem.js";



createApp(App).mount('#app')

四、使用

<script setup lang="ts">
</script>

<template>
  <div>
    測試適配文字大小
  </div>
</template>

<style scoped>
div {
  font-size: 1rem;
}
</style>
user avatar zihuai1949 頭像
1 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.