You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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 with p followed by digits (your percentage classes like p20). 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 demo element 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:08:59