[英]Specific textarea behaviour related to setTimeout
我想做的是给用户一个textarea(具有启用的输入),并允许他最多写10个字符。 实际上, textarea应该允许更多的字符 ,不仅是10 个字符 ,其他字符也应相应地表现:
1º 每当用户使用11ºchar时,都有一个setTimeout 。 所以,我在那儿写东西,我达到了10º的字符数(文本允许的“最大”数),并希望在给定的时间后擦除其他char。
somethinge = 10 chars.
anotherwor = 10 chars.
input: somethingeiefjaiehf
after 5 seconds:
input: somethinge
input: anotherwordtotestthisandseeifitworks
after 5 seconds:
input: anotherwor
2º为此, 我基本上将clearTimeout附加到全局变量:
//Function "countChar(val)" is activated with the keydown event
var timer_to_op = null;
function countChar(val) {
var len = val.value.length; //lenght of input in textarea
clearTimeout(timer_to_op);
//...
//irrelevant code
//...
}else if(len > 140){
$("#status_toOp_num").text(145-len);
timer_to_op = setTimeout(function(){
val.value = val.value.substring(0, 140);
},5000);
}
实际上,由于某种原因,它将无法正常工作。 如果用户正在键入并且他在5秒钟内键入了另一个字符,那么我希望计时器重新启动。
input: anotherwor
input: anotherword (+d) timer = 1...2...3...
input: anotherworde (+e) timer = 1...2...
input: anotherwordef (+f) timer = 1...2...3...4...5!
input: anotherwor the user took more than 5 seconds so it erased the excedent.
希望我能理解我的意思。 关于这个有什么想法吗? 非常感谢你! (我没有放任何html,只是<textarea onclick="countChar(this)">
)
我并不是真的想了解您在代码中正在做什么,这似乎不必要地复杂。
检查这个小提琴。 http://jsfiddle.net/Q2h5f/
的HTML
<textarea id="limitText">0123456789</textarea>
Java脚本
var tarea = document.getElementById("limitText");
tarea.onkeypress = checkInputText;
var timer = null;
function checkInputText(e) {
if (timer) clearTimeout(timer);
timer = setTimeout(limitTextLength, 5000);
}
function limitTextLength() {
var tareaVal = document.getElementById("limitText").value.toString();
if (tareaVal.length > 10) {
tarea.value = tareaVal.slice(0, 10);
}
}
应该解决您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.