Vanilla JS捐赠进度条问题:循环数组添加Div失效,求解决
Hey there! Let's break down what's going wrong with your progress bar code and fix it step by step.
Key Issues in Your Original Code
First, let's spot the bugs that are causing the broken behavior:
- Incorrect loop condition:
for (var i = 0; i < numbers; i++)compares a number to an array, which will never work. You need to loop over the array's length withi < numbers.length. - Wrong width calculation:
div.style.width = numbers + 'px'uses the entire array as a string (like"2,5,25px") instead of the individual donation amount at indexi. - No target limit check: There's no logic to stop adding blocks once the total donations hit £100.
- No support for new donations: The code runs once, but doesn't handle updating the bar when new donations are added (and would duplicate elements if re-run).
Fixed Vanilla JS Code
Here's a revised version that addresses all these issues, with clear separation of logic for calculating totals, rendering the bar, and adding new donations:
// Initial donation array (this will grow as new donations are added) let donated = [2, 5, 25]; // Target amount for the progress bar const TARGET_AMOUNT = 100; // Calculate total donated amount function getTotalDonations() { return donated.map(Number).reduce((sum, donation) => sum + donation, 0); } // Render or update the progress bar function renderProgressBar() { const barContainer = document.querySelector('.bar'); // Clear existing elements to avoid duplicates barContainer.innerHTML = ''; const totalDonated = getTotalDonations(); // If we've hit or exceeded the target, just render a full bar if (totalDonated >= TARGET_AMOUNT) { const fullBar = document.createElement('div'); fullBar.style.background = 'red'; fullBar.style.width = `${TARGET_AMOUNT}px`; fullBar.style.height = '50px'; barContainer.appendChild(fullBar); console.log('Target reached! No more donations needed.'); return; } // Track running total to cap donations at the target let runningTotal = 0; const donations = donated.map(Number); // Loop through each donation to create individual blocks for (let i = 0; i < donations.length; i++) { const donation = donations[i]; // If adding this donation would exceed the target, only use the remaining amount const displayAmount = runningTotal + donation > TARGET_AMOUNT ? TARGET_AMOUNT - runningTotal : donation; const donationBlock = document.createElement('div'); donationBlock.style.background = 'red'; donationBlock.style.width = `${displayAmount}px`; donationBlock.style.height = '50px'; donationBlock.style.float = 'left'; barContainer.appendChild(donationBlock); runningTotal += displayAmount; // Stop looping once we've filled the bar if (runningTotal >= TARGET_AMOUNT) break; } // Optional: Log current progress percentage const progressPercent = (totalDonated / TARGET_AMOUNT) * 100; console.log(`Current progress: ${progressPercent.toFixed(2)}%`); } // Function to add a new donation and update the bar function addNewDonation(amount) { const currentTotal = getTotalDonations(); // Don't add if we've already hit the target if (currentTotal >= TARGET_AMOUNT) { console.log('Cannot add more donations—target already reached!'); return; } // Add the new donation to the array donated.push(amount); // Re-render the progress bar renderProgressBar(); } // Initialize the progress bar on page load renderProgressBar(); // Example usage: Add new donations // addNewDonation(10); // addNewDonation(58); // This will push total to 100 and fill the bar
Recommended CSS for the Bar
Add this to your stylesheet to ensure the progress bar container behaves correctly:
.bar { width: 100px; /* Matches the £100 target */ height: 50px; border: 1px solid #000; overflow: hidden; /* Prevent blocks from spilling outside the container */ }
How This Works
- Modular functions: Separating calculation, rendering, and donation addition makes the code easier to debug and extend.
- Target protection: The code automatically stops adding blocks once the total hits £100, even if new donations would push it over.
- Dynamic updates: Calling
addNewDonation(amount)will update the donation array and re-render the bar without duplicating elements.
内容的提问来源于stack exchange,提问作者Reena Verma
相关产品推荐
相关产品推荐

