第一种
俺写在index.html中的head标签与body标签中间(2560是pc端设计稿的宽度):
<script> //设置 webview 字体大小不受系统修改而改变 (function () { if (window.HiSpaceObject) { window.HiSpaceObject.setTextSizeNormal(); } })(); //屏幕适应 (function (win, doc) { if (!win.addEventListener) return; var html = document.documentElement; function setFont() { var html = document.documentElement; var k = 2560; html.style.fontSize = (html.clientWidth / k) * 100 + "px"; } setFont(); setTimeout(function () { setFont(); }, 300); doc.addEventListener("DOMContentLoaded", setFont, false); win.addEventListener("resize", setFont, false); win.addEventListener("load", setFont, false); })(window, document); </script>
第二种
在utils文件夹下新建rem.js文件(copy别人的代码,因为我拿到的设计稿是1080的宽度,所以用1080来计算):
const setFontSize = (minFontSize = 12, maxFontSize = 16) => { window.onresize = () => { // 7.5根据设计稿的横向分辨率/100得来 var deviceWidth = document.documentElement.clientWidth; // 获取浏览器宽度 if (deviceWidth > 750) { deviceWidth = 10.8 * 50; } else if (!deviceWidth) { return; } // 此时的fontSize大小为50px(375屏幕的时候) document.documentElement.style.fontSize = `${deviceWidth / 10.8}px`; // 禁止双击放大 document.documentElement.addEventListener( "touchstart", function (event) { if (event.touches.length > 1) { event.preventDefault(); } }, false ); var lastTouchEnd = 0; document.documentElement.addEventListener( "touchend", function (event) { var now = Date.now(); if (now - lastTouchEnd <= 300) { event.preventDefault(); } lastTouchEnd = now; }, false ); }; }; export default { setFontSize, };
然后在main.js中引入:
import Rem from "./utils/rem"; Rem.setFontSize();
标签:function,端自,documentElement,适配,pc,setFont,addEventListener,var,document From: https://www.cnblogs.com/nangras/p/17761141.html