如何根据输入的字母数量填充进度条

How to fill progress bar based on number of letters typed?

本文关键字:填充 何根 输入      更新时间:2023-09-26

我正试图使一个输入框底部有一个div,它将作为一个进度条告诉你,当你有足够的字符输入。

我不能让这个动画工作,即使我认为它会容易得多,当我决定尝试这个项目。

请让我知道我的代码有什么问题。谢谢!

<div id='cntnr'>
  <div id='inptDiv'>
    <input id='inpt1'>
    <div id='prgInd'></div>
  </div>
</div> 

var main = function() {
  var inptAmnt = document.getElementById('inpt1').value;
  if(inptAmnt.length === 1) {
    $('#prgInd').css('width', 25);
  }
}
$(document).ready(main);

我也尝试了这个代码,但它也没有工作:

var main = function() {
  var inptAmnt = document.getElementById('inpt1').value;
  if(inptAmnt.length === 1) {
    $('#prgInd').animate({
      width:25
    },200 )
  }
}
$(document).ready(main);

JSFiddle: https://jsfiddle.net/qcsb53ha/

您可以使用jQuery来监听您的文本inputchange, keyuppaste事件。

然后,根据你想要的输入长度计算一个百分比;并使用这个百分比来设置进度条的width

如果"百分比"高于100 -只需将其重新设置为100。jQuery代码如下:

var desiredLength = 4; // no jokes please...
// Listen to the change, keyup & paste events.
$('#text-box').on('change keyup paste', function() {
    // Figure out the length of the input value
    var textLength = $('#text-box').val().length;
    // Calculate the percentage
    var percent = (textLength / desiredLength) * 100;
    // Limit the percentage to 100.
    if (percent > 100) {
      percent = 100;
    }
    // Animate the width of the bar based on the percentage.
    $('.progress-bar').animate({
      width: percent + '%'
    }, 200)
});

查看工作的JSFiddle在这里:https://jsfiddle.net/jqbka5j8/1/

我已经包含了用于设置宽度的普通代码,以及用于设置宽度动画的代码。您可以注释/取消注释必要的代码,并进行适当的测试。

希望这对你有帮助!

不需要使用javascript,你可以只使用纯CSS和Content edit:

HTML

<div>
    <span contenteditable="true">sdfsd</span>
</div>
CSS

span 
{
    border: solid 1px black;
}
div 
{
    max-width: 200px;   
}

JsFiddle示例