思路简介:

1、首先,界面布局的尺寸采用rem单位。
2、然后,通过设置根节点(html)的 font-size 的 px 值 来影响 rem 的实际大小。
3、最后,通过 js 来实时控制font-size 的大小,等比例变换即可。

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <title>rem 适配</title>
  7. <meta name="viewport" content="width=device-width, initial-scale=1">
  8. <style type="text/css">
  9. * {
  10. margin: 0;
  11. padding: 0;
  12. }
  13. .downloadBtn {
  14. width: 10rem;
  15. height: 2rem;
  16. background: #f40;
  17. position: absolute;
  18. left: 50%;
  19. top: 20rem;
  20. margin-left: -6rem;
  21. font-size: 1rem;
  22. }
  23. </style>
  24. </head>
  25. <body>
  26. <div class="content">
  27. <img class="contentImg" id="contentImg" src="./images/content.png"/>
  28. <button class="downloadBtn">点击我,我的位置也不会变化</button>
  29. </div>
  30. <script>
  31. function initWidth() {
  32. document.getElementById("contentImg").style.width = document.documentElement.clientWidth + 'px'
  33. }
  34. function initFontSize() {
  35. const cw = document.documentElement.clientWidth
  36. // width: 375px -> fontSize:16px
  37. if (cw == 375) {
  38. document.documentElement.style.fontSize = '16px'
  39. } else {
  40. document.documentElement.style.fontSize = cw / 375 * 16 + 'px'
  41. }
  42. }
  43. initWidth()
  44. initFontSize()
  45. window.onresize = () => {
  46. initWidth()
  47. initFontSize()
  48. }
  49. </script>
  50. </body>
  51. </html>