Javascript 显示当前滚动条滚动的百分比

<!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

image

Reference

  1. 想法来源:https://es6.ruanyifeng.com/#docs/array
  2. 在线编辑HTML:https://c.runoob.com/front-end/61/
  3. 文档查找:https://developer.mozilla.org/zh-CN/docs/Web/API/Element/scroll_event
posted @ 2023-03-17 13:40  echo_lovely  阅读(273)  评论(0编辑  收藏  举报