How TO - JavaScript プログレスバー

❮ 前章へ 次章へ ❯

JavaScript を使用してプログレスバーの作成方法を学習します。



プログレスバーの作成

ステップ 1) HTML の追加:

<div id="myProgress">
  <div id="myBar"></div>
</div>
ステップ 2) CSS の追加:

アニメーションを可能にするには、アニメーション要素をその「親コンテナ」に相対的にアニメーション化する必要があります。

#myProgress {
    position: relative;
    width: 100%;
    height: 30px;
    background-color: grey;
}
#myBar {
    position: absolute;
    width: 1%;
    height: 100%;
    background-color: green;
}
Try it Yourself »
ステップ 3) JavaScript の追加:

JavaScript を使用してアニメーションを作成する:

function move() {
    var elem = document.getElementById("myBar");
    var width = 1;
    var id = setInterval(frame, 10);
    function frame() {
        if (width >= 100) {
            clearInterval(id);
        } else {
            width++;
            elem.style.width = width + '%';
        }
    }
}
Try it Yourself »

ラベルの追加

ユーザが、プロセスのどの位置にいるかを示すラベルを追加する場合は、プログレスバーの内側(または外側)に新しい要素を追加します:

ステップ 1) HTML の追加:

<div id="myProgress">
  <div id="myBar">
    <div id="label">10%</div>
  </div>
</div>
ステップ 2) CSS の追加:

/* If you want the label inside the progress bar */
#label {
    text-align: center; /* If you want to center it */
    line-height: 30px; /* Set the line-height to the same as the height of the progress bar container, to center it vertically */
    color: white;
}
Try it Yourself »
ステップ 3) JavaScript の追加:

プログレスバーの幅と同じ値にラベル内のテキストを動的に更新する場合は、次を追加します:

function move() {
    var elem = document.getElementById("myBar");
    var width = 10;
    var id = setInterval(frame, 10);
    function frame() {
        if (width >= 100) {
            clearInterval(id);
        } else {
            width++;
            elem.style.width = width + '%';
            document.getElementById("label").innerHTML = width * 1 + '%';
        }
    }
}
Try it Yourself »

❮ 前章へ 次章へ ❯