h5 编写postcsstoviewport插件 px->vw和全局修改文字大小

1.index.html设置meta和清除默认样式

复制代码
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <!-- h5设置宽度为设备宽度,不出现横向滚动条 -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite + Vue + TS</title>
    <style>
      /* 清除默认样式 */
      html,body,#app {
        width: 100%;
        height: 100%;
        overflow: hidden;
      }
      *{
        padding: 0;
        margin: 0;
      }
    </style>
  </head>
  <body>
    <div id="app"></div>
    <script type="module" src="/src/main.ts"></script>
  </body>
</html>
复制代码

2.应用

复制代码
<template>
  <div>
    三栏式布局
  </div>
  <div class="warp">
    <div class="left" @click="change(28)">变大</div>
    <div class="center">中</div>
    <div class="right" @click="change(12)">变小</div>
  </div>
  <h1>适配方法</h1>
  <h1>rem:需要使用flexible.js转rem为px</h1>
  <h1>vw、vh,相对于视口的比例</h1>
  <h1>百分比:相对于父元素的比例</h1>
  </template>
  
  <script setup lang='ts'>
  import { ref, reactive } from 'vue'
  // 使用vueuse库
  import { useCssVar } from '@vueuse/core'
  const change = (num: number) => {
    // 使用use去获取root的css变量,然后修改给全局使用--size变量的同步修改文字大小
    // const size = useCssVar('--size')
    // size.value = num + 'px'
    // 对应的源码设置root的css变量
    document.documentElement.style.setProperty('--size', num + 'px')
    // 获取root的css变量
    // const size = getComputedStyle(document.documentElement).getPropertyValue('--size')
  }
  </script>
  
  <style lang='scss'>
  :root {
    --size: 16px;
  }
  .warp {
    display: flex;
    width: 100%;
    .left {
      width: 100px;
      background-color: red;
      font-size: var(--size);
    }
    .center {
      flex: 1;
      background-color: green;
      font-size: var(--size);
    }
    .right {
      width: 100px;
      background-color: blue;
      font-size: var(--size);
    }
  }
  
  </style>
复制代码

3.插件代码

复制代码
// postcss是vite内置的,不需要安装
import type { Plugin } from 'postcss'; 
const Options = {
  viewportWidth: 375, // 视窗的宽度
}
interface Options {
  viewportWidth: number
}
export const postCsspxToViewport = (options:Options = Options):Plugin  =>{
  const opt = Object.assign({}, Options, options)
  return {
    postcssPlugin: 'postcss-px-to-viewprot',
    // 钩子函数会在css解析的时候调用
    Declaration(node) {
      // 写px转vw的逻辑
      // px可以写任意其他的做匹配,这样可以做到只对某些样式生效
      if (node.value.includes('px')) {
        const num = parseFloat(node.value) // 考虑到有小数
        // 把px转成vw
        node.value = `${((num / opt.viewportWidth) * 100).toFixed(2)}vw`        
      }
    }
  }
}
复制代码

4.插件引入

 

posted on   ChoZ  阅读(11)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示