實現效果:按鈕被滑出屏幕,fix到屏幕下方web
使用requestAnimFrame瀏覽器
window.requestAnimFrame = (() => {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
(callback => { window.setTimeout(callback, 1000 / 60) })
})()
複製代碼
監聽與監聽滾動執行的函數函數
listenScroll(ele, callback) {
if (ele === null || ele === undefined) {
return
}
document.addEventListener('scroll', this.throttle(ele, callback), false)
}
throttle(ele, callback) {
let isRunning = false
return () => {
if (isRunning) return
isRunning = true
// requestAnimationFrame:回調間隔 = 瀏覽器重繪頻率
window.requestAnimationFrame((timestamp) => {
callback(this.check(ele))
isRunning = false
})
}
}
this.listenScroll(document.querySelector('#ele'), (res) => {
// 處理按鈕的展現
})
複製代碼
檢測按鈕是否是到達隱藏條件 這裏是根據按鈕底部到屏幕距離,注意是屏幕ui
checkEleHidden(ele) {
const bottom2top = ele.getBoundingClientRect().bottom
const height = window.innerHeight
return height < bottom2top
}
複製代碼
若是頁面有其餘事件對內容進行影響的話,建議在這些事件結束後再次出發this
this.check(document.querySelector('#ele'))
複製代碼