pc-H5 适配方案

一.介绍  

  在前端项目页面开发中,尤其是H5页面开发,我们常常要适配各种分辨率的屏幕,才能让用户获得最好的体验效果.pc也是如此,很多页面是一屏,也是要适配各种尺寸的分辨率.这时候我们就需要对各种分辨率的手机电脑进行适配.那么用什么适配方案比较好呢?下面给大家介绍一种我觉得比较好的适配方案.

二、分辨率

  常用的分辨率可以大致分为这些,手机:320-750(320-768)   ipad:750-1080(768-1080) pc:1080-1440  1440-1920 1920-2560 2560-3440 3440-5120 。适配的基础通常还是要根据设计稿来决定,比如pc的设计稿宽度是1920,那么你的适配方案只能是1080-1920之间去适配,不能适配大于1920的。那么大于1920的适配,我们就通常采取水平居中,空白地方采用背景平铺或者使用主题色平铺.

三、适配脚本代码

(function() {
      window.onload = window.onresize = () => {
        let clientWidth = document.body.clientWidth;
        // console.log(clientWidth,'clientWidth');
        if (clientWidth >= 750) {
          /* 适配pc页面 最小适配分辨率 12/(20/1920) = 1152 */
          var size = 20 * clientWidth / 1920 + 'px';
          document.documentElement.style.fontSize = size;
        } else {
          /* 淘宝移动端适配解决方案 */
          (function flexible(window, document) {
            var docEl = document.documentElement;
            var dpr = window.devicePixelRatio || 1;
            function setBodyFontSize() {
              if (document.body) {
                document.body.style.fontSize = (12 * dpr) + 'px';
              } else {
                document.addEventListener('DOMContentLoaded', setBodyFontSize);
              }
            }
            setBodyFontSize();
            function setRemUnit() {
              var rem = docEl.clientWidth / 10;
              docEl.style.fontSize = rem + 'px';
            }
            setRemUnit();
            window.addEventListener('resize', setRemUnit);
            window.addEventListener('pageshow', function(e) {
              if (e.persisted) {
                setRemUnit();
              }
            });
            if (dpr >= 2) {
              var fakeBody = document.createElement('body');
              var testElement = document.createElement('div');
              testElement.style.border = '.5px solid transparent';
              fakeBody.appendChild(testElement);
              docEl.appendChild(fakeBody);
              if (testElement.offsetHeight === 1) {
                docEl.classList.add('hairlines');
              }
              docEl.removeChild(fakeBody);
            }
          }(window, document));
        }
      };
    })();

四、写法

  H5:设计稿750*H(H依据设计稿实现长度)  字体:18px;

<div class='al_wrap'></div>
<style>
  @lg: 75rem;
    .al_wrap{
      width: 750/@lg;
      height: 200/@lg;
      overflow: hidden;
      margin: 0 auto;
      font-size: 18/@lg    
    }          
</style>

  pc:设计稿1920*H(H依据设计稿实现长度)字体:20px;距离上20px;

<div class='al_wrap'></div>
<style>
  @lg: 20rem;
    .al_wrap{
      width: 1920/@lg;
      height: 100/@lg;
      overflow: hidden;
      margin: 0 auto;
      margin-top: 20/@lg;
      font-size: 20/@lg    
    }          
</style>
原文地址:https://www.cnblogs.com/xiaoqi2018/p/10635031.html