可视区域判断(js三种方式判断)

时间:2023-02-22 12:01:09

offsetTop,scrollTop,viewPortHeight

  • scrollTop:滚动条滚动的距离
  • offsetTop:元素到offsetParent顶部的距离
  • offsetParent:距离元素最近的一个具有定位的祖宗元素(relative,absolute,fixed),若祖宗都不符合条件,offsetParent为body
  • innerHeight表示窗口内容区域的高度,这是不包括边框、菜单栏的

公式:el.offsetTop - document.documentElement.scrollTop <= viewPortHeight

<div class="content">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
....
</div>
const el = document.getElementId('el')
window.addEventListener('scroll', e => {
isInViewPortOfOne(el)
})

function isInViewPortOfOne(el) {
console.log(el.offsetParent,'offsetParent')//body
// viewPortHeight 兼容所有浏览器写法
const viewPortHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
const offsetTop = el.offsetTop
const scrollTop = document.documentElement.scrollTop
const top = offsetTop - scrollTop
// 这里+100是为了提前加载+ 100
return top <= viewPortHeight +100
}

getBoundingClientRect

获得页面中某个元素的左,上,右和下分别相对浏览器视窗的位置,到浏览器可视范围的距离(不包含文档卷起的部分)

<div ></div>
var object=document.getElementById('box');
rectObject = object.getBoundingClientRect();
  • rectObject.top:元素上边到视窗上边的距离;
  • rectObject.right:元素右边到视窗左边的距离;
  • rectObject.bottom:元素下边到视窗上边的距离;
  • rectObject.left:元素左边到视窗左边的距离;
  • rectObject.width:是元素自身的宽
  • rectObject.height是元素自身的高
function isInViewPortOfTwo(el) {
const viewPortHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
const top = el.getBoundingClientRect() && el.getBoundingClientRect().top
console.log('top', top)
return top <= viewPortHeight + 100
}