嗨,我正在處理 java 腳本中的進度條,我需要它在達到 100% 后將其重置。無限前進。
function start(al) {
var bar = document.getElementById('progressBar');
bar.value = al;
al ;
var sim = setTimeout("start(" al ")", 1);
if (al == 100) {
bar.value = 100;
clearTimeout(sim);
}
}
var amountLoaded = 0;
這僅在頁面重繪 時有效。但它不會自動作業。
uj5u.com熱心網友回復:
使用setTimeout字串而不是使用回呼是不好的做法,因為它呼叫 eval(使其具有安全風險)并且可讀性較差。此外,start您可以使用setInterval. 從那里你可以增加你的bar.value并檢查值是否大于或等于 100 來呼叫clearInterval。在這里,我使用短路來獲得更簡潔的代碼,但如果您愿意,可以將其擴展為 if 陳述句。
function start(initialValue) {
const bar = document.getElementById('progessBar');
bar.value = initialValue;
const sim = setInterval(() => bar.value >= 100 && clearInterval(sim), 1);
}
uj5u.com熱心網友回復:
您應該使用setInterval來呼叫處理遞增的回呼函式progressbar。
如果您想progressbar在一段時間后重置,您可以使用它setTimeout來執行此操作。
這是一個現場演示,它progressbar按10every遞增500ms,一旦達到100%該方法,就會使用該方法將元素從setTimeouthit 重置為0after :2s100%
/** that function will automatically get executed (called an IIFE) */
(function start() {
const bar = document.getElementById('progressBar'),
percentage = document.getElementById('percentage')
interval = setInterval(() => {
/** tells whether the progress bar will be full after this iteration */
const done = bar.value 10 > 100;
/** add 10 to the value */
bar.value = 10;
percentage.textContent = (done ? 100 : bar.value) '%';
/** 100% reached */
if (done) {
/** clear the interval so the callback function will no longer be called */
clearInterval(interval);
percentage.textContent = 'Resetting in 2 seconds...';
/** add a 2s delay till resetting the progressbar */
const timeOut = setTimeout(() => {
bar.value = 0;
percentage.textContent = '0%';
clearTimeout(timeOut);
}, 2000);
}
}, 500); /** the callback is invoked every 500ms */
})();
<progress id="progressBar" max="100" value="0"></progress>
<span id="percentage">0%</span>
您可以玩轉它并應用適合您的值和/或條件。
uj5u.com熱心網友回復:
如果將來有人會尋找這個!這是代碼:
setInterval(function start() {
const bar = document.getElementById('progressBar'),
percentage = document.getElementById('percentage')
interval = setInterval(() => {
const done = bar.value 10 > 100;
bar.value = 10;
percentage.textContent = (done ? 100 : bar.value) '%';
if (done) {
clearInterval(interval);
/** add a 2s delay till resetting the progressbar */
const timeOut = setTimeout(() => {
bar.value = 0;
percentage.textContent = '0%';
clearTimeout(timeOut);
}, 100);
}
}, 80); /** @ths on stack overflow made this */
}, 1000)();
html:
<progress class="progressbar" id="progressBar" max="100" value="0"></progress>
<span id="percentage">0%</span>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/506274.html
標籤:javascript 循环
