note icon indicating copy to clipboard operation
note copied to clipboard

纯CSS实现进度条效果

Open liuyib opened this issue 6 years ago • 0 comments

效果如下:

progress_1

看见这个效果,第一感觉是不可能纯 CSS 实现,需要用 JS 计算滚动距离什么的,但知道原理之后感觉特别有意思。

学 CSS 就像逛海澜之家一样,每次都有新体验 : )

其实这个效果用 线性渐变 就可以实现。

核心代码:

body {
  background-image: linear-gradient(to right top, #fc0 50%, #eee 50%);
  background-repeat: no-repeat;
}

添加上面代码后,效果如下:

progress_2

知道了这点,接下来怎么做就很明显了。我们只需要将多余的部分用元素遮起来即可。

这里我们用一个伪元素,将多余的部分遮住:

body::after {
  content: '';
  z-index: -1;
  position: fixed;
  top: 5px;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
}

效果如下:

progress_3

眼尖的同学可能已经看出来,当滚动条到达底部的时候,滚动条并没有达到100%:

progress_4

解决办法很简单,调整一下渐变大小即可:

body {
   background-image: linear-gradient(to right top, #fc0 50%, #eee 50%);
   background-repeat: no-repeat;
+  background-size: 100% calc(100% - 100vh + 5px);
}

这里使用 calc 进行计算:整个文档的高度减去一个屏幕高度,使得在滚动到底部的时候,进度条刚好走满。而 +5px 则是留出滚动条的高度。

最后,效果就完美实现了:

progress_1

Demo体验地址:https://liuyib.github.io/demo/note/progress-bar/


原文链接: https://juejin.im/post/5c35953ce51d45523f04b6d2

liuyib avatar Jan 12 '19 12:01 liuyib