Kev*_*n.a 1 javascript reactjs
您好,我正在尝试检查用户是否滚动了页面底部。
我正在使用此功能来检查:
const handleScroll = (event) => {
const bottom = event.target.scrollHeight - event.target.scrollTop === event.target.clientHeight;
if(bottom){
console.log('hello');
}
}
Run Code Online (Sandbox Code Playgroud)
但问题是我的应用程序看起来像这样:
现在该功能仅在内部滚动条位于底部时才起作用。但是我希望它在外部滚动条到达底部时触发。
整个代码如下所示:
const handleScroll = (event) => {
const bottom = event.target.scrollHeight - event.target.scrollTop === event.target.clientHeight;
if(bottom){
console.log('hello');
}
}
return (
<div className='main' onScroll = {handleScroll}>
<div className='project-counter'>{filteredProjects.length > 0 ? (<p>Gevonden projecten : {filteredProjects.length}</p>) : null}</div>
{pro.map(project => (
<div className='view-container' key={project._id}>
<div className='hours-container'>
<table>
<tr>
<th className='tb-first'>Datum</th>
<th className='tb-first'>medewerker</th>
<th>Dienst</th>
<th>Toelichting</th>
<th>Aantal</th>
</tr>
{project.projectHours.map(hour => (
<tr>
<td>{hour.created_at}</td>
<td>{hour.employee.name}</td>
<td>{hour.type.label}</td>
<td>{hour.note}</td>
<td>{hour.hours.toFixed(2)}</td>
</tr>
))}
</table>
</div>
</div>
))}
</div>
)
Run Code Online (Sandbox Code Playgroud)
将侦听器添加到窗口对象:
const App = () => {
const handleScroll = () => {
const bottom = Math.ceil(window.innerHeight + window.scrollY) >= document.documentElement.scrollHeight
if (bottom) {
console.log('at the bottom');
}
};
React.useEffect(() => {
window.addEventListener('scroll', handleScroll, {
passive: true
});
return () => {
window.removeEventListener('scroll', handleScroll);
};
}, []);
return <div className = "" > < /div>
};
ReactDOM.render( < App / > , document.getElementById("root"));Run Code Online (Sandbox Code Playgroud)
. {
height: 200vh;
width: 100%;
background-color: mediumseagreen;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.development.js"></script>
<div id="root"></div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1786 次 |
| 最近记录: |