无限滚动的项目数是否不变?

问题描述 投票:2回答:2

我在这里有代码无限滚动。当用户滚动时,它将加载更多20个项目。当我滚动到太多时,它成为一个大列表。

问题

我滚动项目数的方式不变。

我想在应用程序加载新项目时必须删除旧项目

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

// Add 20 items.
var nextItem = 1;
var loadMore = function() {
  for (var i = 0; i < 20; 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: 300px;
  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>
javascript infinite-scroll
2个回答
0
投票

如果您在此之前清空列表,可以吗?

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

// Add 20 items.
var nextItem = 1;
var loadMore = function() {
  listElm.innerHTML = ''
  for (var i = 0; i < 20; 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: 300px;
  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>

0
投票

您可以在每次调用loadMore()时清空列表。

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

// Add 20 items.
var nextItem = 1;
var loadMore = function() {
  //Here we empty the list to remove the old results
  listElm.innerHTML = ''
  //And then load the new items
  for (var i = 0; i < 20; 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();
© www.soinside.com 2019 - 2024. All rights reserved.