如何实现div在用户上滑或不在底部时取消自动向下滚动功能
解决方案
你的代码仅判断了chatBox是否存在active类,但缺少滚动事件监听来动态切换这个类的状态,因此自动滚动逻辑会一直触发。
实现步骤
- 给
chatBox绑定scroll事件,实时判断滚动条位置:当滚动条距离底部大于5px(预留容错值,避免像素计算误差导致判断失效)时,添加active类停止自动滚动;当用户手动滚动回底部时,移除active类恢复自动滚动。 - 原有定时拉取逻辑不用大改,只需要确保滚动判断逻辑提前注册即可。
完整修改后代码
// 提前注册滚动监听事件 chatBox.addEventListener('scroll', () => { // 滚动条距离底部的距离 = 内容总高度 - 滚动条已滚动高度 - 容器可视高度 const isBottom = chatBox.scrollHeight - chatBox.scrollTop - chatBox.clientHeight <= 5 if (isBottom) { chatBox.classList.remove('active') } else { chatBox.classList.add('active') } }) // 原有定时拉取逻辑保持不变 setInterval(() =>{ let xhr = new XMLHttpRequest(); xhr.open("POST", "php/get-chat.php", true); xhr.onload = ()=>{ if(xhr.readyState === XMLHttpRequest.DONE){ if(xhr.status === 200){ let data = xhr.response; chatBox.innerHTML = data; if(!chatBox.classList.contains("active")){ scrollToBottom(); } } } } xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhr.send("incoming_id="+incoming_id); }, 500); function scrollToBottom(){ chatBox.scrollTop = chatBox.scrollHeight; }
补充说明
- 容错值5px可以根据实际场景调整,避免因为滚动条计算的小数精度问题导致判断错误。
- 如果你的
chatBox有padding、border样式,不需要额外调整即可直接运行上述代码。
内容的提问来源于stack exchange,提问作者Azis Sofyan Prasetyo
相关产品推荐
相关产品推荐

