React 判断盒子高度滚动时是否触底(触顶)

28 篇文章 1 订阅
// 触底

isDivScrollBottom = (div) => {
    return div.scrollHeight - div.scrollTop === div.clientHeight;
}

componentDidMount () {
    const myDiv = document.getElementById('myDiv');
    myDiv.addEventListener('scroll', () => {
        if (this.isDivScrollBottom(myDiv)) {
        console.log('Div scrolled to bottom');
        }
    });
}

触底(使用监听以及使用onScorll)

// onScroll

import React, { useRef } from 'react';
 
const MyComponent = () => {
  const boxRef = useRef(null); // 创建 ref 对象
  
  const handleScroll = (event) => {
    if ((boxRef.current.scrollHeight - boxRef.current.clientHeight) === boxRef.current.scrollTop) {
      console.log('已经滑动到底部');
    } else {
      console.log('未滑动到底部');
    }
  };
  
  return (
    <div className="my-container" onScroll={handleScroll} ref={boxRef}>
      {/* 内容 */}
    </div>
  );
};
 
export default MyComponent;



// 监听
import { useEffect, useRef } from 'react';
 
function MyComponent() {
  const boxRef = useRef(null); // 创建 ref 对象
  
  useEffect(() => {
    function handleScroll() {
      if (boxRef.current) {
        const scrollTop = boxRef.current.scrollTop; // 获取滚动条相对于容器顶部的偏移量
        const clientHeight = boxRef.current.clientHeight; // 获取容器可视区域的高度
        const scrollHeight = boxRef.current.scrollHeight; // 获取内容的总高度(包括被隐藏的部分)
        
        if ((scrollTop + clientHeight >= scrollHeight)) {
          console.log('已经滑动到底部');
          // 这里可以添加其他需要执行的操作或者调用其他组件的方法等
        } else {
          console.log('未滑动到底部');
        }
      }
    };
    
    window.addEventListener('scroll', handleScroll); // 监听页面滚动事件
    
    return () => {
      window.removeEventListener('scroll', handleScroll); // 清除事件监听
    };
  }, []);
  
  return <div className="my-container" ref={boxRef}>{/* 此处为盒子内容 */}</div>;
}

触顶

import React, { useRef } from 'react';
 
const MyComponent = () => {
  const boxRef = useRef(null); // 创建 ref 引用
  
  const handleScroll = (event) => {
    if (!boxRef.current || !boxRef.current.clientHeight) return; // 确保有效的 DOM 节点存在并且已经加载完成
    
    const scrollPosition = event.target.scrollTop; // 获取滚动位置
    const isAtTop = scrollPosition === 0; // 判断是否到达顶部
    
    console.log('是否到达顶部', isAtTop);
  };
  
  return <div className="my-container" onScroll={handleScroll} ref={boxRef}>{/* 这里放入盒子内容 */}</div>;
};
 
export default MyComponent;

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值