html 缩放页面样式不乱(动态设置rem的跟字体大小rem布局实现)
主要核心代码(通过动态获取浏览器窗口宽度给html设置font-size,然后使用rem布局实现缩放页面样式不乱掉):
<script> ;(function(win) { var tid; function refreshRem() { let designSize = 1920; // 设计图尺寸 let html = document.documentElement; let wW = html.clientWidth;// 窗口宽度 let rem = wW * 100 / designSize; document.documentElement.style.fontSize = rem + 'px'; } win.addEventListener('resize', function() { clearTimeout(tid); tid = setTimeout(refreshRem, 300); }, false); win.addEventListener('pageshow', function(e) { if (e.persisted) { clearTimeout(tid); tid = setTimeout(refreshRem, 300); } }, false); refreshRem(); })(window); </script>
截不到浏览器的 缩放大小手动输大小吧
放到最小25%:
放到最大500%:
先上列子:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/> <title>Document</title> <style> body, html { margin: 0px; } .wenzi { margin: 0 auto; padding: 0.2rem; width: 3rem; font-size: 0.16rem; box-sizing: border-box; border: 0.03rem solid #61a4f1; text-align: center; } .wenzi img { width: 1rem; margin: 0 auto; } </style> </head> <body> <div class='wenzi'> <p>文字文字文字文字文字文字文字</p> <img src="./东方明珠.png" alt=""> <img src="./东方明珠.png" alt=""> </div> </body> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script> <script> ;(function(win) { var tid; function refreshRem() { let designSize = 1920; // 设计图尺寸 let html = document.documentElement; let wW = html.clientWidth;// 窗口宽度 let rem = wW * 100 / designSize; document.documentElement.style.fontSize = rem + 'px'; } win.addEventListener('resize', function() { clearTimeout(tid); tid = setTimeout(refreshRem, 300); }, false); win.addEventListener('pageshow', function(e) { if (e.persisted) { clearTimeout(tid); tid = setTimeout(refreshRem, 300); } }, false); refreshRem(); })(window); </script> </html>