介绍一个纯 css 的骨架屏方案,核心思想是利用 :empty 来实现的,跨框架

266 阅读1分钟

使用案例

这个是 react 的一个案例,使用的时候,给需要动态获取数据的地方,加上骨架所需 class 就行了

C88.png

vue 也是类似的代码

吐个槽 现在异步加载的界面,分两种情况处理骨架

列表的数据,用菊花来处理,

非列表的带有 DOM 结构的,则用这种 css 骨架来处理,就不用写多一次骨架的结构了

.skeleton {

  /* 骨架动画 */
  @skeleton-style: {
    background-image: linear-gradient(90deg, #f2f2f2 25%, #e6e6e6 37%, #f2f2f2 63%);
    background-size: 400% 100%;
    animation: skeleton-loading 1.4s ease infinite;
  }

  /* 单行,通常用于标题这种单行块元素 */
  &-block:empty::before{
    display: inline-block;
    width: 100%;
    content: 'skeleton';
    text-indent: -999em;
    @skeleton-style();
  }

  /* 内敛,通常用于额外的小信息 */
  &-inline:empty::before {
    display: inline-block;
    content: 'skeleton';
    text-indent: -999em;
    width: 50%;
    @skeleton-style();
  }

  /* 多行,通常用于正文 */
  &-multi:empty {

    &::before {
      display: inline-block;
      width: 100%;
      content: 'skeleton';
      text-indent: -999em;
      margin-bottom: 0.2em;
      @skeleton-style();
    }

    &::after {
      display: inline-block;
      content: 'skeleton';
      text-indent: -999em;
      width: 50%;
      @skeleton-style();
    }

  }

  /* 动画 */
  @keyframes skeleton-loading {
    0% {
      background-position: 100% 50%;
    }

    100% {
      background-position: 0 50%;
    }
  }

}

码客的骨架屏是通过vue-content-loader 手动写的, 这样即使在spa内也可以用

而自动生成的骨架屏一般是首次加载时候出现, 进入spa后就没了