[英]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.