在Jquery进度条中显示百分比

我的页面中有一个动态更新的进度条,我想在中间区分百分比,但我无法弄清楚如何。 这是我页面上的进度条:

这是我更新进度条的jQuery代码:

 $.ajax({ xhr: function () { var xhr = new window.XMLHttpRequest(); xhr.upload.addEventListener("progress", function (evt) { if (evt.lengthComputable) { var pct = evt.loaded / evt.total; $("#prog").css({ width: pct * 100 + '%' }); $('#progress-value').html(pct * 100); } }, false); xhr.addEventListener("progress", function (evt) { if (evt.lengthComputable) { var pct = evt.loaded / evt.total; $("#prog").css({ width: pct * 100 + '%' }); $('#progress-value').html(pct*100); if (pct === 1) { $('#prog').addClass('hide'); } } }, false); return xhr; }, 

Ity更新进度条,因为我看到它在数据加载过程中进展,但它没有显示百分比。 我究竟做错了什么?

我要做的是利用元素上的data-属性(在本例中我将使用data-progress ),以及CSS中该元素的content:属性。

例如JQuery:

 $.ajax({ xhr: function () { var xhr = new window.XMLHttpRequest(); xhr.upload.addEventListener("progress", function (evt) { if (evt.lengthComputable) { var pct = evt.loaded / evt.total; $("#prog").css({ width: pct * 100 + '%' }) .attr('data-progress', pct * 100 + '%'); } }, false); xhr.addEventListener("progress", function (evt) { if (evt.lengthComputable) { var pct = evt.loaded / evt.total; $("#prog").css({ width: pct * 100 + '%' }) .attr('data-progress', pct * 100 + '%'); if (pct === 1) { $('#prog').addClass('hide'); } } }, false); return xhr; }, 

因此,在代码中,您将看到在更新进度条上的物理宽度时,它还会同时更新数据属性。 当然,CSS将使用新值自动更新。

在CSS中,它将是:

 #prog[data-progress] { position: relative; } #prog[data-progress]:before { position: absolute; content: attr(data-progress); left: 50%; top: 50%; transform: translate(-50%, -50%); /* this sets the text to be exactly in the middle of the parent element */ }