实现进度条

发布时间 2023-10-09 21:24:44作者: 张吱吱

通过CSS过渡效果(transition)可以设置宽度的动画过渡。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .progress-bar-container {
            width: 300px;
            height: 20px;
            background-color: #F0F0F0;
            border-radius: 10px;
            overflow: hidden;
        }

        .progress-bar {
            height: 100%;
            background-color: #32CD32; /* 进度条颜色 */
            width: 0%; /* 初始宽度为0% */
            transition: width 0.5s ease-in-out; /* 过渡效果,可自行调整动画时间 */
        }
    </style>
</head>
<body>
    <div class="progress-bar-container">
        <div class="progress-bar"></div>
    </div>
</body>
<script>
    // 获取进度条元素
    const progressBar = document.querySelector('.progress-bar');

    // 设置初始进度为30%
    progressBar.style.width = '30%';

    // 更新进度条进度
    function updateProgress(progress) {
    progressBar.style.width = progress + '%';
    }

    // 示例,假设每隔一秒更新一次进度
    let progress = 30; // 初始进度为30%
    const interval = setInterval(() => {
    progress += 10; // 每次增加10%
    updateProgress(progress);
    
    if (progress >= 100) {
        clearInterval(interval); // 达到100%停止更新
    }
    }, 1000);
</script>
</html>