前端页面自适应设置

1、前端响应式布局的目的

适应不同尺寸设备,使页面展示效果更好

2、rem 原理

根据UI设计稿和设备尺寸的大小比例,动态计算并更改html根元素字体大小,页面使用rem单位自适应缩放
对于一些引入的库,例如swiper、antd carousel 中是不能转换的,只能转自定义的内容

3、 实现方式

要求: 1220 < 内容 <1550

js方式(不推荐)

window.addEventListener('DOMContentLoaded', () => {
    
    
  getRem(1366, 100);
});

// window.onload = function () {
    
    
//   getRem(1366, 100);
// };

window.onresize = function () {
    
    
  getRem(1366, 100);
};

function getRem(pWidth: number, pRem: number) {
    
    
  const html = document.getElementsByTagName('html')[0];
  const oWidth = document.body.clientWidth || document.documentElement.clientWidth;
  if (oWidth >= 1366 && oWidth <= 1646) {
    
    
    html.style.fontSize = (oWidth / pWidth) * pRem + 'px';
  }
}

css 修改

html {
    
    
  font-size: 100px;

  @media (min-width: 1366px) and (max-width: 1646px) {
    
    
    font-size: 100 / 1366vw * 100;
  }

  @media (min-width: 1646) {
    
    
    font-size: 120.4978px;
  }
}

猜你喜欢

转载自blog.csdn.net/weixin_53334387/article/details/127676043