如何从15个class为projects的div中随机选取5个无序展示?编程新手求助
Randomly Display 5 Out of 15 Project Divs (For Beginners)
Hey there! Since you're new to programming, let's walk through a straightforward, no-fuss way to do this with plain JavaScript—no fancy tools required. Here's exactly how you can make it work:
Step 1: The Core Plan
We'll break this into simple, easy-to-follow steps:
- Grab all your
.projectsdivs - Randomize their order reliably
- Pick the first 5 from the randomized list
- Show only those 5 (hide the rest)
Step 2: The Code (With Clear Comments!)
Add this script right before the closing </body> tag in your HTML file (this makes sure all your project divs are loaded before the code runs):
// Wait until the entire page's content is fully loaded document.addEventListener('DOMContentLoaded', function() { // 1. Get all project divs and convert them into an array (easier to work with) const allProjects = Array.from(document.querySelectorAll('.projects')); // 2. Shuffle the array using the Fisher-Yates algorithm (a trusted randomization method) function shuffleArray(array) { for (let i = array.length - 1; i > 0; i--) { // Pick a random index from 0 to i const j = Math.floor(Math.random() * (i + 1)); // Swap elements at positions i and j to shuffle [array[i], array[j]] = [array[j], array[i]]; } return array; } // 3. Shuffle the projects and grab the first 5 const randomProjects = shuffleArray(allProjects).slice(0, 5); // 4. Hide all projects initially allProjects.forEach(project => { project.style.display = 'none'; }); // 5. Show the 5 randomly selected projects randomProjects.forEach(project => { // Replace 'block' with 'flex' or 'grid' if your projects use those layouts originally project.style.display = 'block'; }); });
Step 3: Quick Tips for Your Setup
- If your
.projectsdivs use a display property other thanblock(likeflexorgrid), just swap'block'in the last part to match your original CSS. - Every time someone refreshes the page, they'll get a new random set of 5 projects—perfect for showing variety!
- You don't need to change any of your existing HTML structure—this code works with the
.projectsdivs you already have.
If something doesn't work right away, double-check:
- That your divs actually have the class
projects(no typos!) - That the script is placed after all your project divs in the HTML file.
内容的提问来源于stack exchange,提问作者Yoonseok Lee
相关产品推荐
相关产品推荐

