Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

纯CSS实现进度条效果 #1

Open
liuyib opened this issue Jan 12, 2019 · 0 comments
Open

纯CSS实现进度条效果 #1

liuyib opened this issue Jan 12, 2019 · 0 comments

Comments

@liuyib
Copy link
Owner

liuyib commented Jan 12, 2019

效果如下:

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant