js监听元素是否在屏幕内

实现效果:按钮被滑出屏幕,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'))
复制代码
相关文章
相关标签/搜索