阿里云主机折上折
  • 微信号
Current Site:Index > `<progress>` - progress bar

`<progress>` - progress bar

Author:Chuan Chen 阅读数:59438人阅读 分类: HTML

The <progress> tag is used to display the completion progress of a task on a webpage. It typically appears as a horizontal bar, with the fill proportion reflecting the current progress value. This element supports both determinate progress (known total) and indeterminate progress (unknown total), making it suitable for scenarios like file uploads or form filling.

Basic Syntax of <progress>

<progress> is a double tag with the following basic structure:

<progress value="current_value" max="maximum_value"></progress>
  • value: Current progress value (must be a valid floating-point number).
  • max: Total progress value (defaults to 1.0).

When value is omitted, the progress bar displays an indeterminate state (rendered as striped animations or static gray in different browsers):

<!-- Indeterminate progress -->
<progress></progress>

Attribute Details

Core Attributes

  1. value
    The current completion value, which must be less than or equal to max. If omitted, the progress bar enters an indeterminate state.

  2. max
    The total progress value, which must be a positive number. Defaults to 1.0, in which case value ranges from 0.0 to 1.0.

Global Attributes

Supports all HTML global attributes like id, class, style, etc.:

<progress 
  id="fileProgress" 
  class="custom-bar" 
  style="width: 300px"
  value="35" 
  max="100">
</progress>

Browser Rendering Differences

Different browsers render <progress> with significant stylistic variations:

Browser Determinate State Style Indeterminate State Style
Chrome Green gradient fill Blue striped animation
Firefox Blue fill Gray striped animation
Safari Blue fill Static gray bar

Use CSS to standardize styles:

/* Unify progress bars to red across all browsers */
progress {
  appearance: none;
  height: 20px;
}
progress::-webkit-progress-bar {
  background: #f0f0f0;
}
progress::-webkit-progress-value {
  background: #ff4d4d;
}
progress::-moz-progress-bar {
  background: #ff4d4d;
}

Practical Examples

File Upload Progress

Update dynamically with JavaScript:

<progress id="uploadProgress" value="0" max="100"></progress>
<button onclick="simulateUpload()">Start Upload</button>

<script>
function simulateUpload() {
  const progressBar = document.getElementById('uploadProgress');
  let progress = 0;
  
  const interval = setInterval(() => {
    progress += Math.random() * 10;
    if (progress >= 100) {
      progress = 100;
      clearInterval(interval);
    }
    progressBar.value = progress;
  }, 500);
}
</script>

Multi-Step Task Progress

Display segmented progress:

<progress id="multiStepProgress" max="3"></progress>
<div>
  <button onclick="nextStep(1)">Step 1</button>
  <button onclick="nextStep(2)">Step 2</button>
  <button onclick="nextStep(3)">Step 3</button>
</div>

<script>
function nextStep(step) {
  document.getElementById('multiStepProgress').value = step;
}
</script>

Accessibility Recommendations

  1. Always associate with <label>:

    <label for="taskProgress">Current task progress:</label>
    <progress id="taskProgress" value="50" max="100">50%</progress>
    
  2. Provide fallback content for older browsers:

    <progress value="75" max="100">
      <span class="fallback">75%</span>
    </progress>
    

Differences from <meter>

Feature <progress> <meter>
Purpose Dynamic progress Static measurement
Indeterminate Supported Not supported
Typical Use File uploads, loading Disk usage, poll results
Color Semantics None CSS threshold colors

Example comparison:

<!-- Progress bar: indicates ongoing task -->
<progress value="65" max="100"></progress>

<!-- Meter: indicates static value -->
<meter value="6" min="0" max="10">6/10</meter>

Dynamic Styling Techniques

Modify styles via JavaScript for state changes:

<style>
  .progress-danger::-webkit-progress-value {
    background: #dc3545;
  }
  .progress-warning::-webkit-progress-value {
    background: #ffc107;
  }
</style>

<progress id="statusProgress" value="40" max="100"></progress>
<button onclick="setProgressClass('danger')">Danger State</button>
<button onclick="setProgressClass('warning')">Warning State</button>

<script>
function setProgressClass(type) {
  const bar = document.getElementById('statusProgress');
  bar.className = `progress-${type}`;
}
</script>

Framework Examples

React Component

function ProgressComponent() {
  const [progress, setProgress] = useState(0);

  useEffect(() => {
    const timer = setInterval(() => {
      setProgress(prev => (prev >= 100 ? 0 : prev + 10));
    }, 1000);
    return () => clearInterval(timer);
  }, []);

  return (
    <progress 
      value={progress} 
      max="100"
      aria-label="Processing progress"
    />
  );
}

Vue Directive

<template>
  <progress 
    :value="currentProgress" 
    max="100"
    @click="handleClick"
  ></progress>
</template>

<script>
export default {
  data() {
    return { currentProgress: 0 }
  },
  methods: {
    handleClick() {
      this.currentProgress += 10;
    }
  }
}
</script>

Mobile Adaptation Tips

  1. Touch Area: Ensure progress bar height is at least 44px (Apple Human Interface Guidelines):

    progress {
      min-height: 44px;
      width: 100%;
    }
    
  2. Animation Performance: Avoid performance-heavy properties like box-shadow.

  3. Landscape Adaptation:

    @media (orientation: landscape) {
      progress {
        width: 70vh;
      }
    }
    

Backend API Integration

Real-time progress fetching example (using Fetch API):

const progressBar = document.querySelector('#apiProgress');

async function fetchProgress() {
  const response = await fetch('/api/progress');
  const data = await response.json();
  
  progressBar.value = data.current;
  progressBar.max = data.total;
  
  if (data.current < data.total) {
    setTimeout(fetchProgress, 1000);
  }
}

Custom Animation Effects

Pulse animation implementation:

@keyframes pulse {
  0% { opacity: 0.8; }
  50% { opacity: 0.4; }
  100% { opacity: 0.8; }
}

progress[value]::-webkit-progress-value {
  animation: pulse 2s infinite;
}

Browser Compatibility Data

Browser Minimum Supported Version
Chrome 8+
Firefox 16+
Safari 6+
Edge 12+
Internet Explorer 10+

For IE9 and below, use a polyfill:

<!-- Include progress-polyfill -->
<script src="https://cdn.jsdelivr.net/npm/progress-polyfill@1.0.3/dist/progress.min.js"></script>

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

上一篇:<meter>-标量测量

下一篇:<img>-图像嵌入

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.