<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>奇奇怪怪的滚动条显示</title>
</head>
<style>
#progress {
position: fixed;
top: 0;
left: 0;
height: 3px;
background-color: #0A74DA;
}
#content{
width:80px;
height: 100px;
/* 为了滚动条能出来 */
overflow: auto;
}
</style>
<script type="text/javascript">
document.getElementById("content").addEventListener("scroll", function(e){
console.log(e.target.scrollTop) // 这玩意是滚动距离
console.log("percent",(e.target.scrollTop * 1.0 / (e.target.scrollHeight - e.target.offsetHeight))) // 百分比
document.getElementById("progress").style.width= (e.target.scrollTop * 100.0 / (e.target.scrollHeight - e.target.offsetHeight))+"%"
})
</script>
<body>
<!-- 显示百分比进度 -->
<div id="progress"></div>
<!-- 滚动内容 -->
<div id="content">
zhe shi yi duan wen zi, shi wei le tian chong div yong de, qi guai 200px zhe me chang de ma? you dian chang de guo fen le
</div>
</body>
</html>
Result
Reference
- 想法来源:https://es6.ruanyifeng.com/#docs/array
- 在线编辑HTML:https://c.runoob.com/front-end/61/
- 文档查找:https://developer.mozilla.org/zh-CN/docs/Web/API/Element/scroll_event