跳至主要內容

滚动事件

Yang大约 2 分钟

描述

scroll 事件允许对页面或元素滚动作出反应,在 window 和可滚动元素上都可以运行

window.scrollXwindow.scrollY 用来获取滚动偏移量

window.pageXOffsetwindow.scrollYOffset 分别是前两个的别名

<div id="showScroll">0px</div>
<script>
  window.addEventListener('scroll', function(event) {
    document.getElementById('showScroll').innerHTML = window.pageYOffset + 'px'
  })
</script>

滚动特性

  • 滚动是“弹性的”,在某些浏览器/设备中,可以在文档的顶端或末端稍微多滚动出一点(超出部分显示的是空白区域,然后文档将自动“弹回”到正常状态)
  • 滚动并不精确,滚动到页面末端时,实际上可能距真实的文档末端约 0-50px,
  • 因此,“滚动到末端”应该意味着访问者离文档末端的距离不超过 100px
const htmlElem = document.documentElement
const htmlRect = htmlElem.getBoundingClientRect()
if(htmlRect.bottom > htmlElem.clientHeight + 100){
  // 未滚动到底部
} else {
  // 已滚动到页面底部
}

防止滚动

  • 不能通过在 onscroll 的监听器中使用 event.preventDefault() 来阻止滚动,因为它会在滚动 之后 才触发

  • 在导致滚动的事件监听器中添加 event.preventDefault()

  • CSS overflow: hidden

例子

无限滚动

创建一个无限的页面,当访问者滚动到页面末端时,它会自动将当期日期时间附加到文本中

<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Scroll</title>
  </head>
  <body>
    <h1>Scroll me</h1>
    <script>
      function populate() {
        while (true) {
          const htmlElem = document.documentElement
          const htmlRect = htmlElem.getBoundingClientRect()
          if (htmlRect.bottom > htmlElem.clientHeight + 100) break;
          document.body.insertAdjacentHTML("beforeend", `<p>${new Date()}</p>`)
        }
      }
      window.addEventListener('scroll', populate)
      populate()
    </script>
  </body>
</html>

滚动按钮

页面向下滚动的距离没有超过窗口高度时,按钮不可见

页面向下滚动距离超过窗口高度时,右下角出现回到顶部按钮,如果页面回滚回去,箭头就会消失

单击按钮时,页面将滚动到顶部

<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Scroll</title>
    <style>
      #btn {
        position: fixed;
        right: 12px;
        bottom: 12px;
        z-index: 999;
        display: none;
      }

      h1 {
        height: 50000px;
      }
    </style>
  </head>
  <body>
    <h1>Scroll me</h1>
    <button id="btn">回到顶部</button>
    <script>
      function scroll() {
        const htmlElem = document.documentElement
        const htmlRect = htmlElem.getBoundingClientRect()
        console.log(window.pageYOffset, htmlElem.clientHeight)
        if (window.pageYOffset > htmlElem.clientHeight) {
          btn.style.display = 'inline-block'
        } else {
          btn.style.display = ''
        }
      }
      window.addEventListener('scroll', scroll)
      btn.onclick = function() {
        window.scrollTo(0, 0)
      }
      scroll()
    </script>
  </body>
</html>
上次编辑于:
贡献者: sunzhenyang