rem适配
<head>
<meta
name="viewport"
content="width=device-width,user-scalable=no,initial-scale=1,minimum-scale=1,maximum-scale=1,viewport-fit=cover"
/>
<script type="text/javascript">
// 动态设置 viewport 的 initial-scale
var viewport = document.querySelector("meta[name=viewport]");
var dpr = window.devicePixelRatio || 1;
var scale = 1 / dpr;
viewport.setAttribute(
"content",
"width=device-width," +
"initial-scale=" +
scale +
", maximum-scale=" +
scale +
", minimum-scale=" +
scale +
", user-scalable=no"
);
// 计算 rem font-size
var clientWidth =
document.documentElement.clientWidth || document.body.clientWidth;
clientWidth > 750 && (clientWidth = 750);
var rootFont = (clientWidth / 7.5).toFixed(2); // 以750设计稿为例
document.documentElement.style.fontSize = rootFont + "px";
</script>
</head>
根据视口适配
(function (win, doc) {
let timer = null;
function flexible() {
let deviceWidth = win.screen.width;
deviceWidth > 750 && (deviceWidth = 750);
// 设计稿宽度(以750设计稿为例)
const targetWidth = 750;
const scale = deviceWidth / targetWidth;
let meta = doc.querySelector('meta[name="viewport"]');
if (!meta) {
const meta = doc.createElement("meta");
meta.setAttribute("name", "viewport");
meta.setAttribute(
"content",
`width=device-width,initial-scale=${scale},minimum-scale=${scale},maximum-scale=${scale},user-scalable=no`
);
doc.getElementsByTagName("head")[0].appendChild(meta);
}
if (meta) {
meta.setAttribute(
"content",
`width=device-width,initial-scale=${scale},minimum-scale=${scale},maximum-scale=${scale},user-scalable=no`
);
}
}
win.addEventListener(
"resize",
() => {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
flexible();
}, 300)
},
false
);
flexible();
})(window, document)