(精華)2020年6月28日 Canvas 進度條

愚公搬程式碼發表於2020-06-28
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>進度條</title>
    <style>
        .my-progress {
            width: 200px;
            background: red;
            font-size: 12px;
            width: 0;
            height: 10px;
            line-height: 20px;
            border-radius: 20px;
        }
    </style>
</head>

<body>
    <div id="myDiv" class="my-progress" style="width:0"></div>
    <div id="percent">0%</div>
    <button id="btn">run</button>
    <script>
        var timer;
        //第一種requestAnimationFrame
        btn.onclick = function () {
            myDiv.style.width = '0';
            cancelAnimationFrame(timer); //清楚定時器
            var fun = function () {
                if (parseInt(myDiv.style.width) < 200) {
                    myDiv.style.width = parseInt(myDiv.style.width) + 5 + 'px';
                    percent.innerHTML = parseInt(myDiv.style.width) / 5 + '%';
                    timer = requestAnimationFrame(fun);
                } else {
                    cancelAnimationFrame(timer); //清楚定時器
                }
            }
            timer = requestAnimationFrame(fun);
            // 由系統來決定回撥函式的執行時機,不會有丟幀,卡頓的問題
            // cpu節能
            // 函式節流
            // 相容性:不同的瀏覽器需要加字首
        }
        //第二種setInterval
        btn.onclick = function () {
            clearInterval(timer);
            myDiv.style.width = '0';
            timer = setInterval(function () {
                if (parseInt(myDiv.style.width) < 500) {
                    myDiv.style.width = parseInt(myDiv.style.width) + 5 + 'px';
                    myDiv.innerHTML = parseInt(myDiv.style.width) / 5 + '%';
                } else {
                    clearInterval(timer);
                }
            }, 16);
        }
        //第三種setTimeout
        btn.onclick = function () {
            clearTimeout(timer);
            myDiv.style.width = '0';
            timer = setTimeout(function fn() {
                if (parseInt(myDiv.style.width) < 200) {
                    myDiv.style.width = parseInt(myDiv.style.width) + 5 + 'px';
                    myDiv.innerHTML = parseInt(myDiv.style.width) / 5 + '%';
                    timer = setTimeout(fn, 16);
                } else {
                    clearTimeout(timer);
                }
            }, 16);
        }
    </script>
</body>

</html>

相關文章