Vue3中如何使用rem来控制字体大小

方法一:需要在index.html中写入监听事件

【注】:获取html、body是有特定的方法的

  <script>
    let tid = null;

    function resizeWindow() {
      const docEl = document.documentElement;
      //当前页面的长度
      const HtmlDom = docEl.getBoundingClientRect().width;
      //设置rem
      docEl.style.fontSize = HtmlDom / 192 + "px";
    }

    window.addEventListener("resize", () => {
      this.clearTimeout(tid);
      tid = this.setTimeout(resizeWindow, 300);
    });

    resizeWindow();
  </script>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 3 和 Vite 构建的小程序使用 rem 适配,可以按照以下步骤进行操作: 1. 安装依赖:首先,确保已经安装了 postcss-pxtorem 插件,它可以将 px 单位转换为 rem 单位。可以使用以下命令进行安装: ```bash npm install postcss-pxtorem --save-dev ``` 2. 配置 postcss.config.js:在项目根目录下创建 postcss.config.js 文件,并添加以下配置: ```javascript module.exports = { plugins: { 'postcss-pxtorem': { rootValue: 16, // 设计稿宽度的1/10,如果设计稿是750px,则rootValue为75 propList: ['*'], selectorBlackList: ['html'], // 不转换html选择器的px }, }, }; ``` 3. 修改 Vite 配置:在 vite.config.js 文件,添加对 postcss 的配置。示例代码如下: ```javascript import { defineConfig } from 'vite'; import vue from '@vitejs/plugin-vue'; export default defineConfig({ plugins: [vue()], css: { postcss: { plugins: [require('postcss-pxtorem')], }, }, }); ``` 4. 设置根元素字体大小:在小程序的根组件(如 App.vue,可以设置根元素的字体大小为 rem 单位。示例代码如下: ```vue <template> <div class="container"> <!-- 内容 --> </div> </template> <script> export default { mounted() { document.documentElement.style.fontSize = window.innerWidth / 10 + 'px'; }, }; </script> ``` 现在,你的小程序就可以使用 rem 单位进行适配了。当你在 CSS 文件使用 px 单位时,postcss-pxtorem 插件会自动将其转换为 rem 单位,根据根元素的字体大小进行计算。请确保根据设计稿的宽度设置正确的 rootValue 值,以便正确地适配各种屏幕尺寸。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值