网页顶部添加阅读进度条方法(适用于任何网页)
第一种方法
顶部添加
直接加入html,不需要分别放到css和js里
<!-- 进度条 -->
<style>
progress {
/* position: fixed;
left: 0; */
/* right: 0; */
/* bottom: 0; */
/* top: 0;
width: 100%;
text-align: center;
height: 0.5rem;
border: 1px solid #999;
border-radius: 1rem;
z-index: 5;
-webkit-apperance: none; */
position: fixed;
left: 0;
top: 0;
z-index: 1000;
width: 100%;
height: 2px;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
border: none;
background-color: transparent;
color: #35a935;
}
::-webkit-progress-bar {
background-color: #eee;
border-radius: 1rem;
}
::-webkit-progress-value {
background-color: #169fe6ad;
border-radius: 1rem;
}
</style>
<script>
// 生成元素并添加到文档尾部
var progress = document.createElement('progress');
progress.id = 'progress';
document.body.appendChild(progress);
// 计算当前页面的高度并赋值给进度条
var H;
window.onload = function () {
progress.max = H = home.scrollHeight;
progress.value = 0;
}
// 监听滚动,实时计算滚动条进度值
window.onscroll = function () {
var h = document.documentElement.scrollTop || document.body.scrollTop;
progress.value = h;
var radio = (h / H >= 1) ? 1 : h / H;
progress.innerHTML = progress.title = Math.floor(100 * radio) + '%';
}
</script>
第二种实现方式 (推荐方法)
html加入(html+js,js也可以单独拿出来)
<!-- 顶部进度条 -->
<progress id="content_progress" value="0"></progress>
<script>
document.addEventListener('DOMContentLoaded', function () {
var winHeight = window.innerHeight,
docHeight = document.documentElement.scrollHeight,
progressBar = document.querySelector('#content_progress');
progressBar.max = docHeight - winHeight;
progressBar.value = window.scrollY;
document.addEventListener('scroll', function () {
progressBar.max = document.documentElement.scrollHeight - window.innerHeight;
progressBar.value = window.scrollY;
});
});
</script>
css
/* 顶部进度条css */
#content_progress {
/* Positioning */
position: fixed;
left: 0;
top: 0;
z-index: 1000;
width: 100%;
height: 2px;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
border: none;
background-color: transparent;
color: #35a935;
}
#content_progress::-webkit-progress-bar {
background-color: transparent;
}
#content_progress::-webkit-progress-value {
background-color: #35a935;
}
#content_progress::-moz-progress-bar {
background-color: #35a935;
}