Gli ultimi tutorial di sviluppo web
 

Come - JavaScript Progress Bar


Scopri come creare una barra di avanzamento utilizzando JavaScript.



Creazione di una barra di avanzamento

Fase 1) Aggiungere HTML:

Esempio

<div id="myProgress">
    <div id="myBar"></div>
</div>
Punto 2) Aggiungere CSS:

Per rendere possibile l'animazione, l'elemento animato deve essere animata rispetto al suo "parent container" .

Esempio

#myProgress {
    position: relative;
    width: 100%;
    height: 30px;
    background-color: grey;
}
#myBar {
    position: absolute;
    width: 1%;
    height: 100%;
    background-color: green;
}
Prova tu stesso "
Fase 3) Aggiungi JavaScript:

Creare l'animazione usando JavaScript:

Esempio

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 + '%';
        }
    }
}
Prova tu stesso "

Aggiungere etichette

Se si desidera aggiungere etichette per indicare fino a che punto l'utente è in corso, aggiungere un nuovo elemento all'interno (or outside) la barra di avanzamento:

Fase 1) Aggiungere HTML:

Esempio

<div id="myProgress">
  <div id="myBar">
    <div id="label">10%</div>
  </div>
</div>
Punto 2) Aggiungere CSS:

Esempio

/* 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;
}
Prova tu stesso "
Fase 3) Aggiungi JavaScript:

Se si desidera aggiornare in modo dinamico il testo all'interno dell'etichetta allo stesso valore della larghezza della barra di avanzamento, aggiungere il seguente:

Esempio

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 + '%';
        }
    }
}
Prova tu stesso "