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.插件引入

浙公网安备 33010602011771号