0
点赞
收藏
分享

微信扫一扫

原生JavaScript练习题 08-进度条功能

爱动漫建模 2022-03-11 阅读 74

效果如下:

完整代码:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box {
            width: 400px;
            border: 1px solid #cd2525;
            margin-bottom: 30px;
        }

        .process {
            width: 0px;
            height: 40px;
            background-color: #f0f;
            text-align: center;
            line-height: 40px;
        }
    </style>
</head>

<body>
    <div class="box">
        <div class="process">
            <span>0</span><span>%</span>
        </div>

    </div>
    <button>安装</button>
    <script>
        // 获取元素
        var btn = document.querySelector('button');
        var box = document.querySelector('.box');
        var process = box.querySelector('.process');
        var span = process.querySelector('span');

        let timer = null;
        // 给按钮绑定点击事件
        btn.addEventListener('click', function () {
            let width = 0;
            if (timer == null) { // 保护这个安装的开关,一旦开启,再次点击不受影响
                // 设置定时器
                timer = setInterval(function () {
                    if (width == 400) {
                        clearInterval(timer);
                    } else {
                        width += 4;
                        process.style.width = width + 'px';
                        span.innerHTML = parseInt(width * 100 / 400);
                    }

                }, 100);
            }

        })
    </script>
</body>

</html>
举报

相关推荐

0 条评论