// 触底
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;