使用JavaScript随机数动态修改饼图CSS类名
Dynamic Pie Chart Update with Random Percentage
Got it, let's get your pie chart updating dynamically with that random number. Here's a straightforward way to modify your existing JavaScript code to make this work:
Full Working Code
setInterval(function() { // Generate a random number between 1 and 100 const random = Math.floor(Math.random() * 100) + 1; // Update the demo element to show the current percentage document.getElementById("demo").innerHTML = random; // Grab the pie chart container element const chartElement = document.getElementById("chart"); // Remove any existing percentage class (like p20, p70) const oldPercentClass = Array.from(chartElement.classList).find(className => className.match(/^p\d+$/)); if (oldPercentClass) { chartElement.classList.remove(oldPercentClass); } // Add the new percentage class based on the random number chartElement.classList.add(`p${random}`); }, 1000); // Change 1000 to adjust how often the number updates (in milliseconds)
Breakdown of Key Changes
- Target the Chart Element: We first get the pie chart div using its ID (
chart) so we can manipulate its class list. - Clean Up Old Classes: We use a regex (
/^p\d+$/) to find any existing class that starts withpfollowed by digits (your percentage classes likep20). Removing this old class ensures we don't have conflicting classes on the element. - Add the New Percentage Class: Using template literals, we create the new class name (
p${random}) and add it to the chart element. This tells your CSS to render the correct percentage for the pie chart. - Keep the Number Display: We retain the line that updates the
demoelement so you can still see the numerical value of the random percentage.
This will make your pie chart update in real-time every time the random number changes, matching the percentage shown in the demo element.
内容的提问来源于stack exchange,提问作者staynjokede
相关产品推荐
相关产品推荐

