前言
尝试用vue自定义指令封装常用又功能简单的按钮之类的,因为项目中是使用postcss将style标签中的css做转换,无法在template或js中做转换操作,所以自己了解了rem转换后并将尝试配合用vue自定义指令。
1.rem
这个单位代表根元素(通常为<html> 元素)的 font-size 大小。当用在根元素的 font-size 上面时,它代表了它的初始值。
2.meta标签
name指定了 meta 元素的类型;说明该元素包含了什么类型的信息。content指定了实际的元数据内容。
name="viewport"
meta标签中viewport文档地址
设置移动端中的页面缩放比例等...(注意:只有移动端生效,PC端设置无效)
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=2.0, user-scalable=no"/>
3.设置HTML元素中的font-size
假设设计稿的尺寸为750px
(function (doc, win) {
var docEl = doc.documentElement,
resizeEvt = "orientationchange" in window ? "orientationchange" : "resize",
recalc = function () {
var clientWidth = docEl.clientWidth;
if (!clientWidth) return;
clientWidth = clientWidth >= 750 ? 750 : clientWidth;
var rem = clientWidth / 10;
window.PageRem = rem;
docEl.style.fontSize = rem + "px";
var dpr = parseInt(window.devicePixelRatio);
docEl.setAttribute("dpr", dpr);
};
if (!doc.addEventListener) return;
win.addEventListener(resizeEvt, recalc, false);
doc.addEventListener("DOMContentLoaded", recalc, false);
})(document, window);
4.动态追加一个元素设置上rem
var div = document.createElement("div");
//为div添加样式
var style = document.createAttribute("style");
div.setAttributeNode(style);
div.style.backgroundColor = "#F00";
console.log(window.PageRem);
div.style.width = (733 / 750) * 10 + "rem";
div.style.height = (503 / 750) * 10 + "rem";
//把div追加到body
document.getElementsByTagName("body").item(0).appendChild(div);
5.PostCss
将style标签中的px转换为rem 参考文章
例子
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="x-dns-prefetch-control" content="on" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<!-- // 1、设置视口 -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=2.0, user-scalable=no" />
<style>
* {
margin: 0;
}
</style>
</head>
<body>
<script type="text/javascript">
(function (doc, win) {
var docEl = doc.documentElement,
resizeEvt = "orientationchange" in window ? "orientationchange" : "resize",
recalc = function () {
var clientWidth = docEl.clientWidth;
if (!clientWidth) return;
clientWidth = clientWidth >= 750 ? 750 : clientWidth;
var rem = clientWidth / 10;
window.PageRem = rem;
docEl.style.fontSize = rem + "px";
var dpr = parseInt(window.devicePixelRatio);
docEl.setAttribute("dpr", dpr);
console.dir(docEl, "docEl");
};
if (!doc.addEventListener) return;
win.addEventListener(resizeEvt, recalc, false);
doc.addEventListener("DOMContentLoaded", recalc, false);
})(document, window);
setTimeout(() => {
var div = document.createElement("div");
//为div添加样式
var style = document.createAttribute("style");
div.setAttributeNode(style);
div.style.backgroundColor = "#F00";
console.log(window.PageRem);
div.style.width = (733 / 750) * 10 + "rem";
div.style.height = (503 / 750) * 10 + "rem";
//把div追加到body
document.getElementsByTagName("body").item(0).appendChild(div);
}, 100);
</script>
</body>
<style>
* {
margin: 0;
}
</style>
</html>