通过Oninput属性,触发自定义函数
HTML(已省略Bootstrap引入):
<div class="container">
<div class="starter-template">
<h1>字符输入进度条</h1>
<textarea id="textArea" oninput="textCounter()" class="form-control" rows="3"></textarea>
</div>
<div class="progress">
<div id="showBar" class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">0%</div>
</div>
</div>
Javascript:
function textCounter(){
let num = document.getElementById('textArea').value; //文本域值
let dom = document.getElementById('showBar');//进度条DOM控件
if (num.length < 100){//文本域字数小于100
dom.setAttribute('class','progress-bar'); //样式变更
dom.style="width: " + num.length +"%"; //设定样式百分比
dom.innerText=num.length+"%"; //设定显示值
}else{
//大于100时,固定显示100%
dom.setAttribute('class','progress-bar progress-bar-success progress-bar-striped');
dom.style="width: 100%";
dom.innerText="100%";
}
}
示例文件:textAreaShowBar.html