1. onScrollCapture
html:
// 如果使用typescript, 定义dom类型 private dom: HTMLDivElement | null // ReactJS中,对Div监听只需要绑定 onScrollCapture事件 <div style={{ flex: 1, height: '10000px', overflowY: 'scroll', // 滚动元素需有滚动条 overflowX: 'hidden', }} ref={dom => {this.dom = dom}} onScrollCapture={() => this.handleOnScroll()} > 。。。 </div>
js:
// 监听页面滚动 private handleOnScroll = () => { let flag = false if (this.dom) { const contentScrollTop = this.dom.scrollTop if (contentScrollTop >= 500) { flag = true } this.setState({ flag }, () => { // todo 根据flag 去改变样式或... }) } }
2. addEventListener
useEffect(() => {
const scrollEle = document.getElementById("scrollDom") || document.body; // 获取滚动元素
const handleScroll = (e) => {
// todo
}
scrollEle.addEventListener("scroll", handleScroll);
return () => {
scrollEle.removeEventListener("scroll", handleScroll);
};
}, [])