之前就在其他人的博客上看到了进度条这个功能,由于互联网上并没有可以用的文章,所以我便自己写了一个。
我使用了 <progress>
元素来实现进度条。该元素是在 HTML5 中新加入的。
值得注意的是,该元素在标准中仅仅定义了 属性 value 为已经完成的进度,max 为总进度(值都为正实数),所以该元素实际使用上有一些问题。
目前 Chrome(Webkit)和 FireFox 对其有较好的支持。
核心代码:
HTML
<progress id="top-progress" value="0" max="100"></progress>
JavaScript
document.addEventListener('scroll', () => {
var scrollTopReal = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;//获得滚动条相对页面顶部的距离
var postText = document.getElementsByClassName('post-text')[0];//选取包含文章全文的元素
var postTextTop = postText.offsetTop;//获得该元素据顶部的距离
var articleHeight = postText.clientHeight;//获得该元素的高度(文章长度)
var halfWindow = document.body.clientWidth / 3;//获得1/3个浏览器窗口的高度
var realHeight = halfWindow + scrollTopReal - postTextTop;//计算文章顶部到现在滚动到的位置的距离
var processValue = parseInt((realHeight / articleHeight) * 100);//计算阅读的长度与全文的长度之比,乘以100并输出整数
var topProcess = document.getElementById("top-progress");//选择进度条元素
if (processValue >= 100) {//防止value超过100,不过其实不是必须
var realValue = 100;
} else {
var realValue = processValue;
}
topProcess.value = realValue;//应用进度
});
CSS
progress {
-webkit-appearance: none;//Webkit伪元素支持
width: -webkit-fill-available;//将长度扩展到最大(Webkit),可自行设置
width: -moz-available;//将长度扩展到最大(Mozilla),可自行设置
height: 2px;//进度条高度
background-color: transparent;定义未完成部分的颜色(Mozilla)
border: 0;//清除Firefox默认带的边框
}
::-webkit-progress-bar {//Webkit进度条未完成部分填充颜色
background-color: #E6E6E6;//定义未完成部分的颜色(Webkit)
}
::-webkit-progress-value {//进度条完成的部分(Webkit)
background-color: #57A3E8;
}
::-moz-progress-bar {//进度条完成的部分(Mozilla)
background-color: #57A3E8;
}
参考:https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/progress