判断一个元素是否在可视区域

offsetTop scrollTop clientHeight

利用offsetTop获取元素到顶部的距离, scrollTop滚动条滚动的距离, clientHeight窗口高度

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <title>Document</title>
  8. <style>
  9. .p {
  10. width: 100px;
  11. height: 100px;
  12. border: 1px solid #ddd;
  13. margin-left: 50px;
  14. margin-top: 50px;
  15. }
  16. .a {
  17. margin-top: 800px;
  18. width: 100px;
  19. height: 100px;
  20. border: 1px solid #ddd;
  21. margin-left: 50px;
  22. }
  23. </style>
  24. </head>
  25. <body>
  26. <div class="bg">
  27. <div class="p">p</div>
  28. <div class="a">a</div>
  29. </div>
  30. <script>
  31. const p = document.querySelector('.p')
  32. const a = document.querySelector('.a')
  33. window.addEventListener('scroll', function (e) {
  34. // 滚动的距离
  35. const top = document.documentElement.scrollTop || document.body.scrollTop
  36. // 当前窗口的高度
  37. const clientHeight = window.innerHeight ||
  38. document.documentElement.clientHeight ||
  39. document.body.clientHeight
  40. const aHieght = a.clientHeight
  41. const pHieght = p.clientHeight
  42. console.log(e, top, p.offsetTop, a.offsetTop, clientHeight)
  43. // if (top + clientHeight > p.offsetTop) {
  44. // console.log('p出现了')
  45. // }
  46. // if (top > p.offsetTop + p.clientHeight) {
  47. // console.log('p消失了')
  48. // }
  49. if (top + clientHeight > a.offsetTop) {
  50. console.log('a出现了')
  51. }
  52. if (top > a.offsetTop + a.clientHeight) {
  53. console.log('a消失了')
  54. }
  55. })
  56. </script>
  57. </body>
  58. </html>

getBoundingClientRect

利用getBoundingClientRect返回值是一个 DOMRect对象,拥有left, top, right, bottom, x, y, width, 和 height属性,除了widthheight 以外的属性是相对于视图窗口的左上角来计算的

  1. // partiallyVisible 默认false,部分出现不算出现
  2. const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
  3. const { top, left, bottom, right } = el.getBoundingClientRect()
  4. return partiallyVisible ?
  5. ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) && ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth)) :
  6. top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth
  7. }