通过监听scroll事件,判断容器的scrollTop、clientHeight和scrollHeight实现了下拉触底自动加载的效果,但是这种情况必须是子元素高度的总和大于父容器的高度时,也就是说父容器要有滚动条时才会生效。
但是存在这么一种情况:页面初始时子元素高度的总和与父容器的高度相同或者子元素高度综合小于父容器高度时,不会出现滚动条,导致不会触发scroll事件。请问这种情况如何处理?
以下是我的代码:
#container {
height: 200px;
overflow-x: hidden;
}
.ele {
height: 50px;
width: 100%;
}
let container = document.getElementById("container");
container.onscroll = () => {
if (container.scrollTop + container.clientHeight >= container.scrollHeight) {
console.log('reached!');
}
}
item1
item2
item3
item4
item1
item2
item3
item4
item5
这种情况挺常见的,还请大佬不吝赐教!