web前端入门到实战:css实现的骨架屏方案

优点

  • 简单,不需要工程,不用puppeteer生成骨架dom,也不需要二次开发维护
  • 定制程度高,想怎么搞就怎么搞
  • 不臃肿,只给你想要的

缺点

  • 自动化程度低,需要在骨架dom上手动添加类
  • 协同要求高,不像工程化能通过工程去约束

思路

通过伪元素实现骨架样式,通过操作样式实现骨架和页面的动态切换

实现

css部分(scss写法)

通过after伪元素生成骨架样式,并通过absolute覆盖到实际元素上

专门建立的学习Q-q-u-n: 784-783-012 ,分享学习的方法和需要注意的小细节,不停更新最新的教程和学习技巧
(从零基础开始到前端项目实战教程,学习工具,全栈开发学习路线以及规划)
  .skt-loading {
    pointer-events: none; /* 加载中阻止事件 */
    .skeleton {
      position: relative;
      overflow: hidden;
      border: none !important;
      border-radius: 5px;
      background-color: transparent !important;
      background-image: none !important;
      &::after {
        content: '';
        position: absolute;
        left: 0;
        top: 0;
        z-index: 9;
        width: 100%;
        height: 100%;
        background-color: #EBF1F8;
        display: block;
      }

      /* 下面这部分都是自定义的,看需求修改 */
      &:not(.not-round)::after {
        border-radius: 4px;
      }
      &:not(.not-before)::before {
        position: absolute;
        top: 0;
        width: 30%;
        height: 100%;
        content: "";
        background: linear-gradient(to right,rgba(255,255,255,0) 0,
            rgba(255,255,255,.3) 50%,rgba(255,255,255,0) 100%);
        transform: skewX(-45deg);
        z-index: 99;
        animation: skeleton-ani 1s ease infinite;
        display: block;
      }
      &.badge {
        &::after {
          background-color: #F8FAFC;
        }
      }
    }
  }

  @keyframes skeleton-ani { /* 骨架屏动画 */
    from {
      left: -100%;
    }
    to {
      left: 150%;
    }
  }

html部分

只需要在你认为合理的骨架粒度元素上添加skeleton类即可

js部分

控制好skt-loading类的切换

使用注意

  • after伪元素无法插入到inputimg等非容器元素中,所以如果需要添加skleton,则需要再加一层元素将其包裹
  • 对于像vuereact数据驱动页面需要先有mock数据以生成dom

猜你喜欢

转载自blog.51cto.com/14592820/2463910