纯css实现页面滚动显示进度条效果

  • Post author:
  • Post category:其他


如何不借助 JS,巧妙的实现顶部绿色的滚动进度条,随着页面的滚动进度而变化长短呢?(js实现涉及页面滚动距离的计算,比较麻烦)

废话不多说,实现如下:

我们可以使用

线性渐变

来实现这个功能

假设我们的页面被包裹在

<body>

中,可以滚动的是整个 body,给它添加这样一个从左下到到右上角的线性渐变:

此时,是这样的效果:

绿色块的颜色变化其实已经很能表达整体的进度了,

然后运用一个伪元素,把多出来的部分遮住

可以发现滑到底的时候,进度条并没有到底,这是因为

body

的线性渐变高度设置了整个 body 的大小,我们调整一下渐变的高度就可以了

使用了

calc

进行了运算,减去了

100vh

,也就是减去一个屏幕的高度,这样渐变刚好在滑动到底部的时候与右上角贴合。而

+ 5px

则是滚动进度条的高度,预留出

5px

的高度。再看看效果


完美!!!

整个代码:

<!DOCTYPE html>

<html lang=”en”>

<head>

<meta charset=”UTF-8″>

<meta http-equiv=”X-UA-Compatible” content=”IE=edge”>

<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>

<title>Document</title>

</head>

<body>

There are moments in life when you miss someone so much that you just want to pick them from your dreams and hug them

for real! Dream what you want to dream;go where you want to go;be what you want to be,because you have only one life

and one chance to do all the things you want to do.

May you have enough happiness to make you sweet,enough trials to make you strong,enough sorrow to keep you

human,enough hope to make you happy? Always put yourself in others’shoes.If you feel that it hurts you,it probably

hurts the other person, too.

The happiest of people don’t necessarily have the best of everything;they just make the most of everything that

comes along their way.Happiness lies for those who cry,those who hurt, those who have searched,and those who have

tried,for only they can appreciate the importance of people

who have touched their lives.Love begins with a smile,grows with a kiss and ends with a tear.The brightest future

will always be based on a forgotten past, you can’t go on well in lifeuntil you let go of your past failures and

heartaches.

When you were born,you were crying and everyone around you was smiling.Live your life so that when you die,you’re

the one who is smiling and everyone around you is crying.

Please send this message to those people who mean something to you,to those who have touched your life in one way or

another,to those who make you smile when you really need it,to those that make you see the brighter side of things

when you are really down,to those who you want to let them know that you appreciate their friendship.And if you don’t,

don’t worry,nothing bad will happen to you,you will just miss out on the opportunity to brighten someone’s day with

this message.

</body>

</html>

<style>

body {

position: relative;

padding: 50px;

font-size: 24px;

line-height: 30px;

background-image: linear-gradient(to right top, green 50%, #eee 50%);

background-repeat: no-repeat;

background-size: 100% calc(100% – 100vh + 5px);

z-index: 1;

}

body::after {

content: “”;

position: fixed;

top: 5px;

left: 0;

bottom: 0;

right: 0;

background: #fff;

z-index: -1;

}

</style>



版权声明:本文为weixin_42297355原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。