-1

我正在尝试实现无限滚动。

但不是窗口对象,目标是带有滚动条的子 div。

有没有办法用 JavaScript 检查子 div 的当前高度?

例如,我想在滚动到最后时请求一个事件。

这是我的模板代码。

<div
          style="overflow-y: scroll; height:500px;"
          class="scroll-content"
          @scroll="onScroll"
>
4

2 回答 2

1

这是一个例子:

var listElm = document.querySelector('#infinite-list');

// Add items.
var nextItem = 1;
var loadMore = function() {
  for (var i = 0; i < 10; i++) {
    var item = document.createElement('li');
    item.innerText = 'Item ' + nextItem++;
    listElm.appendChild(item);
  }
}

// Detect when scrolled to bottom.
listElm.addEventListener('scroll', function() {
  if (listElm.scrollTop + listElm.clientHeight >= listElm.scrollHeight) {
    loadMore();
  }
});

// Initially load some items.
loadMore();
#infinite-list {
  /* We need to limit the height and show a scrollbar */
  width: 200px;
  height: 100px;
  overflow: auto;

  /* Optional, only to check that it works with margin/padding */
  margin: 30px;
  padding: 20px;
  border: 10px solid black;
}

/* Optional eye candy below: */
li {
  padding: 10px;
  list-style-type: none;
}
li:hover {
  background: #ccc;
}
<ul id='infinite-list'>
</ul>

于 2020-08-19T17:44:20.543 回答
1

以下函数返回,用户是否滚动到某个元素的底部:

function scrollEnd(el) {
    return (el.scrollTop + el.offsetHeight >= el.scrollHeight);
}

如果将此添加到滚动事件侦听器:

element.addEventListener('scroll', () => {
    if (scrollEnd(element)) {
        // the user reached the end
    }
})

我在 textarea 上试过这个,不过应该适用于任何东西。

于 2020-08-19T17:57:12.330 回答