【Bootstrap】重寫Bootstrap進度條ProgressBar完美實現文字居中
阿新 • • 發佈:2018-12-24
先看下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住: