这是我的HTML:
<input type="text" name="hostname" onkeypress="return keyPressHostName(event)">
这是我的JS:
function keyPressHostName(e) {
var input = e.keyCode ? e.keyCode : e.charCode;
if ((input >= 48 && input <= 57) // 0-9
|| (input >= 65 && input <= 90) //a-z
|| (input >= 97 && input <= 122) //A-Z
|| (input == 45) // dash (-)
|| (input == 46) // point(.)
|| (input == 37) // left key (<-)
|| (input == 39) // right key (->)
|| (input == 8) // backspace
|| (input == 9) // tab
)
return true;
else
return false;
}
/*alert(input);
if ((e.keyCode==45)||(e.keyCode==46)||(e.keyCode==37)||(e.keyCode==39)||(e.keyCode==8)||(e.keyCode==9)||(e.keyCode==39))
return true;
else if ((e.charCode>=48 && e.charCode<=57)||(e.charCode>=65 && e.charCode<=90)||(e.charCode>=97 && e.charCode<=122)||e.charCode==45||e.charCode==46)
return true;
else
return false;
*/
但有一些错误
答案 0 :(得分:1)
所以我的剧本就像这样
<input type="text" name="hostname" onkeypress="return keyPressHostName(event)">
和js是这样的:
function keyPressHostName(e)
{
if (navigator.appName=="Opera")
{
var c= String.fromCharCode(e.keyCode);
if ((e.keyCode==37)// left
||(e.keyCode==8)// <== backspace
||(e.keyCode==9)// tab
||(e.keyCode==39)// right
)return true;
else if (/\_/.test(c))return false;
else if (/[\w\-\.]/.test(c))return true;
else return false;
}
else if (navigator.appName =="Netscape")
{
var c= String.fromCharCode(e.charCode);
if (/\_/.test(c))return false;
else if (/[\w\-\.]/.test(c))return true;
else if (e.keyCode>=1)return true;
else return false;
}
else if (/Microsoft/.test(navigator.appName)){
var c= String.fromCharCode(e.keyCode);
if (/\_/.test(c))return false;
else if (/[\w\-\.]/.test(c))return true;
else return false;
}
else
{
var CharKey = (e.keyCode)?e.keyCode:e.charCode;
var c= String.fromCharCode(CharKey);
if (/\_/.test(c))return false;
else if (/[\w\-\.]/.test(c))return true;
else return false;
}
}
答案 1 :(得分:0)
要获取特殊密钥,onkeypress
应更改为onkeyup
或onkeydown
编辑:
<input type="text" name="hostname" onkeyup="return keyPressHostName(event)">