Javascript 与setTimeout相关的特定textarea行为
我想做的是给用户一个文本区域(启用输入),并允许他最多写10个字符。实际上,文本区域应该允许更多字符,而不仅仅是10个字符,其他字符会相应地进行操作: 1º每当用户使用11º字符时,都会有一个设置超时。所以,我在那里写了一些东西,我达到了字符数10º(文本允许的“最大值”),并希望在给定的时间后删除另一个字符Javascript 与setTimeout相关的特定textarea行为,javascript,jquery,html,google-chrome,settimeout,Javascript,Jquery,Html,Google Chrome,Settimeout,我想做的是给用户一个文本区域(启用输入),并允许他最多写10个字符。实际上,文本区域应该允许更多字符,而不仅仅是10个字符,其他字符会相应地进行操作: 1º每当用户使用11º字符时,都会有一个设置超时。所以,我在那里写了一些东西,我达到了字符数10º(文本允许的“最大值”),并希望在给定的时间后删除另一个字符 somethinge = 10 chars. anotherwor = 10 chars. input: somethingeiefjaiehf after 5 seconds: inp
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,它只是
)我没有真正尝试理解你在代码中做什么,看起来不必要的复杂
看看这把小提琴
HTML
应该可以解决您的问题。与使用计时器相比,使用键控侦听器更好。幸好您添加了一行看似不重要的HTML;)再次释放按键时,键入不会触发
onclick
事件,它会触发onkeydown
、onkeypress
和onkeydup
onclick
仅用于鼠标单击。我知道,我添加了一行看似不重要的HTML错误:p它实际上是onkeyup,并且工作正常:p无论如何!就是这样。非常感谢(我还分别显示了字符数和警告颜色,这就是代码的原因)非常感谢!:)@用户3050963很高兴知道。如果你接受它作为一个为他人省力的答案,那就太好了。
<textarea id="limitText">0123456789</textarea>
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);
}
}