当前位置: 无忧屋首页 > 文章中心 > 前端 >

利用JavaScript判断页面宽度的响应式布局方法

来源:网络

发布人:天道酬勤

发布时间:2024-01-29

分享一个我自用的响应式网站布局方法,非常简单好用。利用JavaScript判断页面宽度,结合rem单位, 实时修改网站尺寸,达到响应式布局方法。

首先前端开发中,样式尺寸单位全部用rem,比如:

  1. .content{
  2. width: 8rem;
  3. border-radius: 0.15rem;
  4. font-size: 0.95rem;
  5. letter-spacing: 0.15rem;
接着页面中的html给个默认的font-size样式,比如:
  1. <html style="font-size: 100px;">
或者
  1. <style>
  2.         html{font-size: 100px;}
  3.     </style>
最后就是利用JavaScript判断页面宽度,实时修改html的font-size的大小。
  1.    
  2. [backcolor=rgb(255, 255, 255)]   [/backcolor]<script>
  3.     const doc = document.documentElement
  4.         window.onresize = () => {
  5.             // 获取窗口宽度
  6.             let width = doc.clientWidth
  7.             // 设备宽度 / 设计稿宽度 = 根元素html大小 / 设计稿根元素大小(假设为100px)
  8.             // 假设我们的设计稿宽度为 750px
  9.             if (width >= 1080) {
  10.                 doc.style.fontSize = '100px'
  11.             } else {
  12.                 doc.style.fontSize = width / 1080 * 100 + 'px'
  13.             }
  14.             console.log(width)
  15.         }
  16.     </script>

免责声明:文中图文均系网友发布,转载来自网络,如有侵权请联系右侧客服QQ删除,无忧屋网友发布此文仅为传递信息,不代表无忧屋平台认同其观点。