如果预先填充了文本区域,如何显示剩余字符?

时间:2019-05-26 11:55:00

标签: javascript jquery html css

如果我已经预填充了textarea,则250个字符实际上不会计算其中已经存在的默认单词。仅当您开始在其中输入内容时,它才会开始计数。

此外,如何在“剩余100个字符”上将文本颜色更改为黄色,而在“剩余0个字符”上更改为红色

有人可以帮忙吗?

function handle(){
  let element = document.getElementById('input')
  let value = element.value
  let maxLength = element.maxLength
  document.getElementById('remaining').innerText = `${maxLength - Number(value.length)} characters remaining`
  
}
<textarea col="8" rows="8" maxlength='250' onkeyup="handle()" id="input" value="">Hello World. Im born today.</textarea>
<p id='remaining'>250 characters remaining</p>

1 个答案:

答案 0 :(得分:3)

  

这250个字符实际上并不计算其中已经存在的默认单词。仅当您开始在其中输入内容时,它才会开始计数。

只需在页面加载时运行一次函数即可:

function handle() {
  let element = document.getElementById('input')
  let value = element.value
  let maxLength = element.maxLength
  document.getElementById('remaining').innerText = `${maxLength - Number(value.length)} characters remaining`
}

handle();
<textarea col="8" rows="8" maxlength='250' onkeyup="handle()" id="input" value="">Hello World. Im born today.</textarea>
<p id='remaining'>250 characters remaining</p>

  

如何在“剩余100个字符”上将文本颜色更改为黄色,而在“剩余0个字符”上更改为红色

对每个if做一个keyup

function handle() {
  let element = document.getElementById('input');
  let value = element.value;
  let maxLength = element.maxLength;
  document.getElementById('remaining').innerText = `${maxLength - Number(value.length)} characters remaining`;

  if (maxLength - Number(value.length) == 0) {
    document.getElementById('remaining').style.color = "red";
  } else if (maxLength - Number(value.length) <= 100) {
    document.getElementById('remaining').style.color = "yellow";
  }
}

handle();
<textarea col="8" rows="8" maxlength='250' onkeyup="handle()" id="input" value="">Hello World. Im born today.</textarea>
<p id='remaining'>250 characters remaining</p>