【看板自适应模板构建】PC端实现适配

1,462 阅读2分钟

方案一 使用rem的css3属性。

rem相对于根元素(即html元素)font-size计算值的倍数。(所有font-size的默认值都是16px)

举个例子

现在在 1920px设计稿一块区域,假设宽度273px,高度随意。那么在1366px屏幕上宽度应该显示多少呢?我们将屏幕宽度等比分成100份

//1920分辨率屏幕
avg = 1920 / 100 = 19.20 px

//1366分辨率屏幕
avg = 1366 / 100 = 13.66 px

在1366分辨率屏幕应该显示宽度 = (1366 * 273) / 1920 最后是194.228125px

//1920分辨率屏幕定义根
font-size = 19.20px //即 1rem = 19.20px

//1366分辨率屏幕
font-size = 13.66px  //即 1rem = 13.66px

适配代码

html{
  font-size:19.20px;  /*默认以设计稿为基准*/
}
@media only screen and (max-width: 1366px) {
  html{
     font-size:13.66px;
  }
}
#controller{
  width:14.21875rem;
}

id为controller的盒子在1920屏幕宽度= 14.21875 * 19.20 最后是273

id为controller的盒子在1366屏幕宽度= 14.21875 * 13.66 最后是194.228125

这样一来我们就适配了1920px和1366px屏幕,兼容了这两个分辨率屏幕。css3属性在IE9+上还是可以使用的。

用个sass/less计算的方法:

// PX 转 rem
@function pxRem($px, $base-font-size: 19.2px) {
  @if (unitless($px)) { //有无单位
    @return ($px / 19.2) * 1rem;
  } @else if (unit($px) == em) {
    @return $px;
  }
  @return ($px / $base-font-size) * 1rem;
}

测试下上面的方法

#controller{
   width:pxRem(273px) 
}
//输出
#controller{
   width:14.21875rem;
}

缺点就是:这里计算可能就产生一系列小数,会有一点模糊。

查阅资料,市场目前大屏幕分辨率显示器大概是

960,1024,1280,1360,1366,1400,1600,1920,2048 (可能后续还有补充) 

方案二、根据不同的分辨率,加载不同的CSS样式文件(定制话,毕竟屏幕那么贵)

<script>
    // 分辨率大于等于1680,大部分为1920的情况下,调用此css
    if(window.screen.width >= 1680){
        document.write('<link rel="stylesheet" href="css/index_1920.css">');
    }
    // 分辨率再在1600-1680的情况下,调用此css
    else if(window.screen.width >= 1600){
        document.write('<link rel="stylesheet" href="css/index_1600.css">');
    }
    // 分辨率小于1600的情况下,调用此css
    else{
        document.write('<link rel="stylesheet" href="css/index.css">');
    }
</script>

全屏适配?