/**
* 判断某一个元素是否在可视区
* 目标元素中心点在滚动区域的可视区内就返回true
* @param {HTMLElement} exporsureDom ListItem组件的dom
* @param {undefined | HTMLElement} scrollDom - 外层包裹的可滚动的父元素,默认为document
* @returns {boolean} boolean
*/
export function whetherDomVisible(exporsureDom, scrollDom = undefined) {
if (!(exporsureDom instanceof HTMLElement)) {
console.info(`"exporsureDom"参数不正确,应该是一个dom对象`)
return false
}
const targetPosition = exporsureDom.getBoundingClientRect()
if (targetPosition) {
const { left: targetleft, top: targetTop, height: targetHeight, width: targetWidth } = targetPosition
if (targetHeight === 0 || targetWidth === 0) return false // 可能是display:none的状态
let wrapLeft = 0
let wrapTop = 0
let wrapRight = window.innerWidth
let wrapBottom = window.innerHeight
// 如果是外部包裹元素在滚动,需要修正判断范围
if (scrollDom instanceof HTMLElement) {
const { left, right, top, bottom } = scrollDom.getBoundingClientRect()
if (left >= wrapLeft && left <= wrapRight && top >= wrapTop && top <= wrapBottom) {
if (right < wrapRight) wrapRight = right
if (bottom < wrapBottom) wrapBottom = bottom
}
}
// 简化计算量,判断中心点是否在屏幕区域内
const centerX = targetleft + targetWidth / 2
const centerY = targetTop + targetHeight / 2
if (centerX >= wrapLeft && centerX <= wrapRight && centerY >= wrapTop && centerY <= wrapBottom) {
return true
}
}
return false
}
console