判断一个元素是否在可视区域
offsetTop scrollTop clientHeight
利用offsetTop获取元素到顶部的距离, scrollTop滚动条滚动的距离, clientHeight窗口高度
<!DOCTYPE html><html lang="en"><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>Document</title><style>.p {width: 100px;height: 100px;border: 1px solid #ddd;margin-left: 50px;margin-top: 50px;}.a {margin-top: 800px;width: 100px;height: 100px;border: 1px solid #ddd;margin-left: 50px;}</style></head><body><div class="bg"><div class="p">p</div><div class="a">a</div></div><script>const p = document.querySelector('.p')const a = document.querySelector('.a')window.addEventListener('scroll', function (e) {// 滚动的距离const top = document.documentElement.scrollTop || document.body.scrollTop// 当前窗口的高度const clientHeight = window.innerHeight ||document.documentElement.clientHeight ||document.body.clientHeightconst aHieght = a.clientHeightconst pHieght = p.clientHeightconsole.log(e, top, p.offsetTop, a.offsetTop, clientHeight)// if (top + clientHeight > p.offsetTop) {// console.log('p出现了')// }// if (top > p.offsetTop + p.clientHeight) {// console.log('p消失了')// }if (top + clientHeight > a.offsetTop) {console.log('a出现了')}if (top > a.offsetTop + a.clientHeight) {console.log('a消失了')}})</script></body></html>
getBoundingClientRect
利用getBoundingClientRect返回值是一个 DOMRect对象,拥有left, top, right, bottom, x, y, width, 和 height属性,除了width 和 height 以外的属性是相对于视图窗口的左上角来计算的
// partiallyVisible 默认false,部分出现不算出现const elementIsVisibleInViewport = (el, partiallyVisible = false) => {const { top, left, bottom, right } = el.getBoundingClientRect()return partiallyVisible ?((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) && ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth)) :top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth}
