移动端rem是比较常见布局方式,本着不重复造轮子的原则,如下直接拷贝可用,不必重复写。
setRem.ts
(function(doc, win) {
var docEl = doc.documentElement,
resizeEvt = "orientationchange" in window ? "orientationchange" : "resize",
recalc = function() {
if (docEl.clientWidth > 750) {
docEl.style.fontSize = "100px";
doc.getElementById("app").style.width = "750px";
} else {
var width = docEl.clientWidth / 7.5;
docEl.style.fontSize = width + "px";
doc.getElementById("app").style.width = "auto";
}
};
if (!doc.addEventListener) return;
win.addEventListener(resizeEvt, recalc, false);
doc.addEventListener("DOMContentLoaded", recalc, false);
})(document, window);
useRem.ts
import { getCurrentInstance } from 'vue';
import { MapConsts } from '@/common/consts/MapConsts';
import { getPageClientWidth } from './usePagePosition';
const baseFont = 100; // 字体大小基准值
// 计算rem
const setRem = () => {
// 相对于750像素的缩放比
const clientWidth = getPageClientWidth();
let scale = clientWidth / 375;
// 根据屏幕变化 1rem 对应的 font-size
// scale = scale > 1 ? 1 : scale;
// const ratio = Math.max(parseFloat(window.devicePixelRatio.toFixed(2)), 1)
const realFont = baseFont * scale;
document.documentElement.style.fontSize = realFont + 'px';
// 根据视口计算vh
// let vh = window.innerHeight * 0.01
// document.documentElement.style.setProperty('--vh', `${vh}px`)
};
// 初始化rem
export const initRem = () => {
// 初始化rem
setRem();
// 获取全局属性变量
const instance = getCurrentInstance();
const globalProperties = instance.appContext.config.globalProperties;
// 改变窗口大小时重新设置 rem
window.addEventListener(MapConsts.RESIZE, () => {
setRem();
// 视窗大小变化监听
globalProperties.$observer.$emit(MapConsts.HANDLERR_ESIZE);
});
};
使用在css样式中
.subtitle-box {
margin-top: .10rem;
padding: 0rem .62rem;
text-align: center;
list-style: none;
font-weight: 400;
font-size: .12rem;
word-wrap: break-word;
color: #333333;
}
点赞加关注,永远不迷路
网友评论