控制div滚动到可视区域再播放动画(包括初始位置在可视区域上方、向上滚动再执行动画)
控制条件主要是两个要素:
盒子的上边框到可视区域下边框的距离要大于零(top替代)
盒子下边框到可视区域上边框的距离要大于零(bottom替代)
参考了这张图:
image.png
以及getBoundingClientRect( )方法
getBoundingClientRect( )方法会返回一组矩形的集合
var box=document.getElementById('box'); // 获取元素
alert(box.getBoundingClientRect().top); // 元素上边距离页面上边的距离
alert(box.getBoundingClientRect().right); // 元素右边距离页面左边的距离
alert(box.getBoundingClientRect().bottom); // 元素下边距离页面上边的距离
alert(box.getBoundingClientRect().left); // 元素左边距离页面左边的距离
top的计算方法采用了
可视窗口的高度-Math.abs(元素上边距离页面上边的距离)
绝对值的原因是因为当div整个在可视窗口上方时元素上边距离页面上边的距离是负值
bottom= 元素下边距离页面上边的距离
实例代码
windowScroll () {
const bottom = document.querySelector('.fade').getBoundingClientRect().bottom
const client = document.documentElement.clientHeight
const top = client - Math.abs(document.querySelector('.fade').getBoundingClientRect().top)
const coop = document.querySelector('.fade')
console.log(bottom, 'bottom')
console.log(top, 'top')
if (bottom > 0 && top > 0) {
coop.classList.add('coop')
// coop.style.visibility = 'visible'
}
}
参考:https://blog.csdn.net/weixin_42557996/article/details/103158928?utm_medium=distribute.pc_relevant_bbs_down.none-task-blog-baidujs-1.nonecase&depth_1-utm_source=distribute.pc_relevant_bbs_down.none-task-blog-baidujs-1.nonecase
https://developer.mozilla.org/zh-CN/docs/Web/API/Element/getBoundingClientRect