页面阅读进度

#JavaScript 2021/03/24 22:50:59

获取当前页面的阅读进度

window.addEventListener('scroll', () => {
  //页面总高度
  const totalHeight = document.body.clientHeight || document.documentElement.scrollHeight
  //当前视窗所占高度
  const viewHeight = document.documentElement.clientHeight || window.innerHeight
  //总体可供滚动的高度
  const scrollLength = totalHeight - viewHeight
  //当前已滚动的高度
  const scrolledHeight = document.documentElement.scrollTop || document.body.scrollTop
  //滚动比例
  const currentProcess = scrolledHeight / scrollLength
  console.log(currentProcess)
})