JS 判断页面是否滚动到底部或滚动到顶部

原生判断

window.addEventListener('scroll', scroll)

function scroll() {
      const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
      const clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
      const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
      
      if (scrollTop === 0) {
        console.log('滚动到顶了');
      }
      if (scrollTop + clientHeight >= scrollHeight - 100) {
        console.log('滚动到底了');
      }
}

window.removeEventListener('scroll', scroll) // 移除滚动事件

scrollTop:文档在可视区上沿的位置距离文档顶部的距离

clientHeight:可视区的高度

scrollHeight:文档总高度

100:用于在滚动到底部之前提前加载内容(如瀑布流),提高用户体验,请自行修改数值(建议不小于 2 像素,以规避在部分浏览器上因获得值为小数时可能无法触发的问题)


jQuery 判断

window.addEventListener('scroll', scroll)

function scroll() {
    const doc_height = $(document).height();
    const scroll_top = $(document).scrollTop();
    const window_height = $(window).height();
    
    if (scroll_top === 0) {
      console.log('滚动到顶了');
    } else if (scroll_top + window_height >= doc_height - 100) {
      console.log('滚动到底了');
    }
}


xoyozo 2 年前
转载请注明出处
云服务器 精选特惠
可能相关的内容