版权声明:原创 https://blog.csdn.net/hangvane123/article/details/84940304
先看下Bootstrap默认的进度条样式
可以看到在.progress-bar内的文字显示在进度条已完成部分,在.progress内的文字显示在进度条未完成部分。
综合考虑了各种因素:
- 文字层需要浮在.progress-bar层上方
- 文字层需要能设置为width:100%,也就是能获取到parent元素的width,从而使text-align: center有效,能够文字居中
- 当.progress被parent元素压缩到显示不全文字时,文字要换行,同时需要自动拓展.progress(和.progress-bar的高度)来容纳下换行的文字
为了实现这些要求反复尝试了很多次,最终终于搞定了:
CSS:
.progress {
margin-bottom: 0px;
height: auto;
position: relative;
}
.progress-bar {
position: absolute;
z-index: 10;
}
.progress-placeholder {
float: left;
width: 100%;
text-align: center;
visibility: hidden;
}
.progress-text {
position: absolute;
z-index: 20;
width: 100%;
text-align: center;
}
JS:
function getProgressStr(str, width, type, striped, active) {
/**
* 动态生成文字居中的Bootstrap ProgressBar
* @return {string} 返回包含progressBar的HTML string
* @param {string} str - 需要显示的文字
* @param {string} width - 进度条占比,CSS代码
* @param {string} type - 进度条类型['danger'|'warning'|'info'|'success']
* @param {Boolean} striped - 是否有条纹
* @param {Boolean} active - 是否有动画
*/
var result = '<div class="progress"><div class="progress-placeholder">{str}</div><div class="progress-text">{str}</div><div class="progress-bar{type}{striped}{active}" style="width: {width};"></div></div>';
result = result.replace(/{str}/g, str);
result = result.replace(/{width}/, width);
result = result.replace(/{type}/, ' progress-bar-' + type);
result = result.replace(/{striped}/, striped == 1 ? ' progress-bar-striped' : '');
result = result.replace(/{active}/, active == 1 ? ' active' : '');
return result;
}
使用方法:
var progress1 = getProgressStr('进度条要显示的内容', '40%', 'danger', 1, 1);
$('body').append(progress1);
效果:
最终效果:
文字显示不下也能hold住: