前端内容占位技术分享

所谓内容占位技术,意思是说在内容比较多,数据量大的情况下,可以事先将一些标签替代它们的位置,等到加载完毕的时候再将其隐藏。注意这和以前的图片懒加载不是一个意思,两个不起冲突,图片懒加载的原理就是事先用一个较小的loading图片,等用户到达这个位置的高度时再去获取相应的数据。内容占位技术就是模拟它可能会显示出来的样子。

比如下面这个页面,不好意思打了马赛克

再还没有加载内容出来时,我们可以这样。

因为是gif的图片,效果并不是特别好,直接把上面代码拷贝到你的文件里面打开。这里只做了一部分(量宽高太麻烦了)

其中代码

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>dome</title>
  <style>
    body{
      640px;
      margin:0 auto;
      background-color:#fff;
    }
    @keyframes placeHolderShimmer{
        0%{
            background-position: -640px 0
        }
        100%{
            background-position: 640px 0
        }
    }
    .box {
        animation-duration: 1s;
        animation-fill-mode: forwards;
        animation-iteration-count: infinite;
        animation-name: placeHolderShimmer;
        animation-timing-function: linear;
        background: #f6f7f8;
        background: linear-gradient(to right, #eeeeee 8%, #dddddd 18%, #eeeeee 33%);
        background-size: 800px 104px;
        position: relative;
        height:100vh;
    }
    [class^="box-"]{
      position:absolute;
      background-color:#fff;
    }
    .box-bar-0{
      left:60px;
      top:0;
      10px;
      height:50px;
    }
    .box-bar-1{
      left:60px;
      top:0;
      calc(100% - 50px);
      height:20px;
    }
    .box-bar-2{
      left:60px;
      top:calc(60px - 25px);
      calc(100% - 50px);
      height:20px;
    }
    .box-bar-3{
      right: 0;
        top: 20px;
         25%;
        height: 16px;
    }
    .box-bar-4{
      left: 0;
        top: 50px;
         100%;
        height: 16px;
    }
    .box-bar-5{
      left: 110px;
        top: 66px;
         20px;
        height: 132px;
    }
    .box-bar-6{
      left: 110px;
        top: 86px;
         calc(100% - 110px);
        height: 10px;
    }
    .box-bar-7{
      left: 220px;
        top: 98px;
         300px;
        height: 10px;
    }
    .box-bar-8{
      left: 110px;
        top: 110px;
         calc(100% - 110px);
        height: 48px;
    }
    .box-bar-9{
      left: 272px;
        top: 166px;
         calc(100% - 110px);
        height: 12px;
    }
    .box-bar-10{
      left: 272px;
        top: 184px;
         calc(100% - 110px);
        height: 12px;
    }
  </style>
</head>
<body>
  <div class="box">
    <div class="box-bar-0"></div>
  <div class="box-bar-1"></div>
  <div class="box-bar-2"></div>
  <div class="box-bar-3"></div>
  <div class="box-bar-4"></div>
  <div class="box-bar-5"></div>
  <div class="box-bar-6"></div>
  <div class="box-bar-7"></div>
  <div class="box-bar-8"></div>
  <div class="box-bar-9"></div>
  <div class="box-bar-10"></div>
  </div>
</body>
</html>

代码的原理其实很简单,就是用一个大盒子把里面的子盒子包起来,这个大盒子的作用就是那个闪烁效果以及默认背景颜色,其他子标签的作用就是把不是内容的用白色盖住默认背景。

恭喜你看完了,能看下来也是不错的。

原文地址:https://www.cnblogs.com/pssp/p/5924404.html