javascript OnKeyUp、OnKeyDown 和 onKeyPress
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5442842/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
OnKeyUp,OnKeyDown and onKeyPress
提问by Deniz Zoeteman
I try to use all here in this combination:
我尝试在这种组合中使用 all :
<SCRIPT LANGUAGE="JavaScript">
function CountLeft(field, count, max)
{
if (field.value.length > max)
field.value = field.value.substring(0, max);
else
count.value = max - field.value.length;
}
</SCRIPT>
<input name="text" onKeyDown="CountLeft(this.form.text, this.form.left,50);"
onKeyUp="CountLeft(this.form.text,this.form.left,50);" onKeyPress="return entsub(event)">
<input readonly type="text" name="left" size=3 maxlength=3 value="50">
characters left
But the enter key to submit does not work here, can anyone tell me how I can fix that? Oh and, I am trying to make a counter here.
但是提交的输入键在这里不起作用,谁能告诉我如何解决这个问题?哦,我想在这里做一个计数器。
Thanks!
谢谢!
回答by Joan Salvatella
I needed that script too and the one given by Kooilnc didn't really work for me. I used this:
我也需要那个脚本,而 Kooilnc 提供的那个脚本对我不起作用。我用过这个:
function keyhandler(obj,e,max){
e = e || event;
max = max || 140;
var keycode = e.keyCode
, len = 0
, This = keyhandler
, currlen = obj.value.length;
if (!('countfld' in This)){
This.countfld = document.getElementById('letter-count');
}
if (keycode === 13) {
//return document.forms[0].submit();
return true;
}
if (currlen >= max) {
This.countfld.innerHTML = '0';
return false;
}
This.countfld.innerHTML = (max - obj.value.length);
return true;
}
}
And in the HTML file I used this:
在我使用的 HTML 文件中:
<input type="text" onkeyup="return keyhandler(this,event,140)">
I hope it works for you! :D
我希望这个对你有用!:D
回答by KooiInc
Actually, you don't need all these keyhandlers. One keydown handlerwould be sufficient.
实际上,您不需要所有这些密钥处理程序。一个keydown 处理程序就足够了。
The here given function keyhandler
stops updating the text input value after max
is reached and submits the form if the key pressed was enter
. You can find an example @ http://jsfiddle.net/KooiInc/2hrt7/.
这里给定的函数keyhandler
在max
到达后停止更新文本输入值,如果按下的键是 ,则提交表单enter
。你可以在@ http://jsfiddle.net/KooiInc/2hrt7/找到一个例子。
<input type="text" onkeydown="return keyhandler(this,event,50)"/>
now keyhandler looks like this:
现在密钥处理程序看起来像这样:
function keyhandler(obj,e,max) {
e = e || event;
max = max || 50;
console.log(e.keyCode);
if (e.keyCode === 13) {
return document.forms[0].submit();
}
if (obj.value.length >= max && e.keyCode>46) {
return false;
}
return true;
}
By the way, you are aware of the maxlength
attribute of a text input field?
顺便说一句,您知道maxlength
文本输入字段的属性吗?