纯JS实现超出9个filterDiv后隐藏及加载更多功能
.filterDiv Elements and Add Load More Functionality Got it, let's fix this up so you can hide the 10th+ .filterDiv elements and toggle them with the Load More button. Here's a step-by-step breakdown:
Step 1: Hide Extra Elements on Initial Load
First, we'll grab all .filterDiv elements, check if there are more than 9, and hide everything starting from the 10th one (remember, JavaScript uses 0-based indexing, so the 10th element is at index 9).
Update your existing code to this:
const filterDivs = document.querySelectorAll('.filterDiv'); const htCount = filterDivs.length; const loadMoreBtn = document.querySelector('#loadMore'); // Hide elements beyond the 9th one if count exceeds 9 if (htCount > 9) { // Loop from index 9 (10th element) to the last one for (let i = 9; i < htCount; i++) { filterDivs[i].classList.add('hide'); } // Show the Load More button loadMoreBtn.classList.add('show'); }
Don't forget to add CSS for the .hide class to actually hide the elements:
.hide { display: none; }
Step 2: Add Load More Button Functionality
Now we need to make the button show the hidden elements. You can choose between two common approaches:
Option 1: Show All Hidden Elements at Once
This will reveal every hidden .filterDiv when the button is clicked, then hide the button itself:
loadMoreBtn.addEventListener('click', () => { // Remove the hide class from all filterDivs filterDivs.forEach(div => div.classList.remove('hide')); // Hide the Load More button since there's nothing left to load loadMoreBtn.classList.remove('show'); });
Option 2: Load Elements in Batches (e.g., 3 at a Time)
If you prefer a gradual load (better for large lists), this will show 3 more elements each time the button is clicked, and hide the button once everything is visible:
// Track how many elements are currently visible (starts at 9) let currentVisibleCount = 9; loadMoreBtn.addEventListener('click', () => { // Calculate how many more elements to show (max 3, or whatever's left) const nextVisibleCount = Math.min(currentVisibleCount + 3, htCount); // Show the next batch of elements for (let i = currentVisibleCount; i < nextVisibleCount; i++) { filterDivs[i].classList.remove('hide'); } // Update the visible count currentVisibleCount = nextVisibleCount; // Hide the button if all elements are now visible if (currentVisibleCount >= htCount) { loadMoreBtn.classList.remove('show'); } });
That's it! This setup will handle hiding extra elements on page load and letting users reveal them with the Load More button.
内容的提问来源于stack exchange,提问作者user4889134

