如何阻止无限滚动加载到页面顶部?

How to stop infinite scroll from loading on top of page?

当无限滚动接近尾声时,它会加载回页面顶部并刷新。

如何停止它以便它加载新图像和以前的图像,并阻止它重新加载到顶部并刷新?

我不想在收藏夹部分实现无限滚动,只在显示内容部分实现。

感谢任何帮助,谢谢。

const resultsNav = document.getElementById('resultsNav');
const favouritesNav = document.getElementById('favouritesNav');
const imagesContainer = document.querySelector('.images-container');
const saveConfirmed = document.querySelector('.save-confirmed');
const loader = document.querySelector('.loader');


// Unsplash API
const count = 10;
const apiKey = 'UNSPLASH_API_KEY';
const apiUrl = `https://api.unsplash.com/photos/random?client_id=${apiKey}&count=${count}`;

let resultsArray = [];
let favourites = {};


function showContent(page) {
  window.scrollTo({ top: 0, behavior: 'instant'});
  if (page === 'results') {
    resultsNav.classList.remove('hidden');
    favouritesNav.classList.add('hidden');
  } else {
    resultsNav.classList.add('hidden');
    favouritesNav.classList.remove('hidden');
  }
  loader.classList.add('hidden');
}

function createDOMNodes(page) {
  const currentArray = page === 'results' ? resultsArray : Object.values(favourites);
  currentArray.forEach((result) => {
    // Card Container
    const card = document.createElement('div');
    card.classList.add('card');
    // link
    const link = document.createElement('a');
    link.href = result.links.html;
    link.target = '_blank';

    //Images
    const image = document.createElement('img');
    image.src = result.urls.regular;
    image.alt = 'Image';
    image.loading = 'lazy';
    image.classList.add('card-img-top');
    //Card Body
    const cardBody = document.createElement('div');
    cardBody.classList.add('card-body');
    // Save Text
    const saveText = document.createElement('p');
    saveText.classList.add('clickable');
  if (page === 'results') {
    saveText.textContent = 'Add To Favourites';
    saveText.setAttribute('onclick', `saveFavourite('${result.urls.regular}')`);
  } else {
    saveText.textContent = 'Remove Favourite';
    saveText.setAttribute('onclick', `removeFavourite('${result.urls.regular}')`);
  }

    // Append
    cardBody.append(saveText);
    link.appendChild(image);
    card.append(link, cardBody);
    imagesContainer.appendChild(card);
  });
}

function updateDOM(page) {
  // Get Favourites from localStorage
  if (localStorage.getItem('unsplashFavourites')) {
    favourites = JSON.parse(localStorage.getItem('unsplashFavourites'));
  }
  imagesContainer.textContent = '';
  createDOMNodes(page);
  showContent(page);
}

//  Get 10 Images from Unsplash API
async function getUnplashPictures() {
// Show loader
loader.classList.remove('hidden');
  try {
    const response = await fetch(apiUrl);
    resultsArray = await response.json();
    updateDOM('results');
  } catch (error) {
    // Catch Error Here
  }
}

// Add result to Favourites
function saveFavourite(itemUrl) {
  // Loop through Reuslts Array to select Favourite
  resultsArray.forEach((item) => {
    if (item.urls.regular.includes(itemUrl) && !favourites[itemUrl]) {
      favourites[itemUrl] =item;
      // Show Save Confirmation for 2 Seconds
      saveConfirmed.hidden = false;
      setTimeout(() => {
        saveConfirmed.hidden = true;
      }, 2000);
      // Set Favourites in localStorage
      localStorage.setItem('unsplashFavourites', JSON.stringify(favourites));
    }
  });
}

// Remove item from Favourites
function removeFavourite(itemUrl) {
  if (favourites[itemUrl]) {
    delete favourites[itemUrl];
    // Set Favourites in localStorage
    localStorage.setItem('unsplashFavourites', JSON.stringify(favourites));
    updateDOM('favourites');
  }
}

// Check to see if scrolling near bottom of page, Load More Photos
window.addEventListener('scroll', () => {
  if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 1000) {
    getUnplashPictures();
  }
});

// On Load
getUnplashPictures();

问题出在你的两行代码中。首先,如评论中所述,

window.scrollTo({ top: 0, behavior: 'instant'});

是将页面滚动到顶部的原因,您应该将其删除。 另一个问题在获取逻辑中:

resultsArray = await response.json();

删除整个列表的内容,用新的记录代替!这意味着您在加载更多数据时不会将新数据添加到 already-fetched 记录中,而是将当前数据替换为新数据。

可能的解决方案:

const newResultsArray = await response.json();
resultsArray = resultsArray.concat(newResultsArray); // Combine new and already-fetched records

我更改了 jsfiddle 中的这两行并尝试使用模拟数据(api 给出错误)。它对我有用。