前端PC版的简单适配

2,698 阅读1分钟

我们都知道对于前端pc版本的适配是一个难题,大部分都是做的媒体查询。但是有时间公司不要媒体查询 就是需要不管多大的屏幕都是满屏显示。我就在考虑为啥不用rem给pc端做个适配。 下面手机基于设计图是1920的做的简单的js适配。

<script type="text/javascript">
  var winWidth = document.documentElement.offsetWidth ||
  document.body.offsetWidth
  winWidth = winWidth < 1366 ? 1366 : winWidth
  var oHtml = document.getElementsByTagName('html')[0]
  oHtml.style.fontSize = 100 * winWidth / 1920 + 'px'
  
  window.addEventListener('resize', function () {
  var winWidth = document.documentElement.offsetWidth || document.body.offsetWidth
  winWidth = winWidth < 1400 ? 1400 : winWidth
  var oHtml = document.getElementsByTagName('html')[0]
  oHtml.style.fontSize = 100 * winWidth / 1920 + 'px'
  })
</script>

把这个js脚本放到根目录下,也就是index.html中。我们所测的尺寸去除以100就可以转化位rem。

顺便说一句,我的项目是vue所搭建的。当然现在是vue-cli3的话,就放在public文件下的index文件中。

这样就完成了简单的pc端适配

原文地址

PC端使用rem进行屏幕适配 How to do 假定设计稿宽度为 1600px,某个box设计稿宽度为400px。

html {
    font-size: 16px; // 设计稿宽度/100 => 1rem = 16px
}
#box {
    width: 25rem; // 400px/16px
}

@media only screen and (max-width: 1366px) {
   html{
      font-size:13.66px; // 1rem = 13.66px
   }
}

工具

  • Sass
@function px2rem($px, $base-font-size) {
  @if (unitless($px)) { //unitless函数判断有无单位,无单位返回true
    @return ($px / $base-font-size) * 1rem;
  } @else if (unit($px) == em) {//函数取出传入参数的单位 px/em/rem..
    @return $px;
  }
  @return ($px / $base-font-size) * 1rem;
}
#box {
    width: px2rem(400, 16);
}
//编译为
#box {
    width: 25rem;
}

原文地址