控制div滾動到可視區(qū)域再播放動畫(包括初始位置在可視區(qū)域上方囤捻、向上滾動再執(zhí)行動畫)
控制條件主要是兩個要素:
盒子的上邊框到可視區(qū)域下邊框的距離要大于零(top替代)
盒子下邊框到可視區(qū)域上邊框的距離要大于零(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