destroy() {
window.removeEventListener('scroll', this.scrollEvent)
}
// 单个元素
observeSelectTools() {
const selectTools = document.querySelector('.select-tools') as HTMLDivElement
const { height } = selectTools.getBoundingClientRect() // 获取元素的位置 返回{s}
selectTools.style.height = `${height}px`
// boundingClientRect:目标元素的矩形区域的信息
// intersectionRatio:目标元素的可见比例,即intersectionRect占boundingClientRect的比例,完全可见时为1,完全不可见时小于等于0
const io = new window.IntersectionObserver(
([{ boundingClientRect, intersectionRatio }]) => {
if (boundingClientRect.top > 0 && intersectionRatio < 1) {
return false
}
this.fixedSelect = intersectionRatio < 1
return true
},
// 当目标元素和根元素相交的面积占目标元素面积的百分比到达或跨过某些指定的临界值时就会触发回调函数
{ threshold: [0, 1] }
)
io.USE_MUTATION_OBSERVER = false
// 观察目标元素
io.observe(selectTools)
// 针对有的手机出现浮动的bug
window.addEventListener('scroll', this.scrollEvent)
}
// 多个元素时
observeSelectTools() {
const selectTools = document.querySelector(`.select-tools-${this.activeName}`) as HTMLDivElement
const parent = selectTools.parentNode as HTMLDivElement //获取当前元素的父元素
const { height } = selectTools.getBoundingClientRect() // 方法返回元素的大小及其相对于视口的位置
if (height > 0) {
selectTools.style.height = `${height}px`
}
// boundingClientRect:目标元素的矩形区域的信息
// intersectionRatio:目标元素的可见比例,即intersectionRect占boundingClientRect的比例,完全可见时为1,完全不可见时小于等于0
const io = new window.IntersectionObserver(
([{ boundingClientRect, intersectionRatio }]) => {
if (parent.getBoundingClientRect().height === 0
|| (boundingClientRect.top > 0 && intersectionRatio < 1)) {
return false
}
this.fixedSelect = intersectionRatio < 1
return true
},
// 当目标元素和根元素相交的面积占目标元素面积的百分比到达或跨过某些指定的临界值时就会触发回调函数
{ threshold: [0, 1] }
)
io.USE_MUTATION_OBSERVER = false
// 观察目标元素
io.observe(selectTools)
// 针对有的手机出现浮动的bug
window.addEventListener('scroll', this.scrollEvent)
}
scrollEvent() {
timer && clearTimeout(timer)
timer = setTimeout(() => {
const selectTools = document.querySelector('.select-tools') as HTMLDivElement
if (!selectTools) return
const { top } = selectTools.getBoundingClientRect()
if (top > 0) {
this.fixedSelect = false
}
}, 100)
}
IntersectionObserver观察一个元素是否在视窗可见
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
相关阅读更多精彩内容
- 孤单的是人,寂寞的是心。 这只是我写的一个简单的demo,但是所需数据与逻辑已走通, 拿走就能用的那种,希望你能看...
- 最近写了一个VUE的web app项目,需要实现某个部位吸顶的效果。即,页面往上滑动,刚好到达该部位时,该部分,固...