onkeydown onkeypress onkeyup

$("#abc").keydown(function(){

return false;

})

上面这行代码在opera10下面居然没起作用,其它浏览器都可以。onkeydown在opera下没办法阻止浏览器默认行为吗??

本来是为了在input输入框只能输入数字,就用了onkeydown,结果opera10下不起作用

<input type="text" value="" id="a"/>

 

<script type="text/javascript">

 

 

 

 

 

if(window.attachEvent){

$("a").attachEvent("onkeydown",checknum)

}else{

$("a").addEventListener("keydown",checknum,false);}

function checknum(e){

if((e.keyCode>47 && e.keyCode<58) || (e.keyCode>95 && e.keyCode<106) || e.keyCode == 8){

 

     //do some thing

}

else{

if (e.preventDefault) {

e.preventDefault();

} else {

window.event.returnValue = false;

}

 

}

}

function $(id){

return document.getElementById(id) || id;

}

</script>

很纠结,查了很久,发现网上也有人遇到这种问题,后来有人建议用onkeypress代替。试了下,onkeypress貌似还真的可以,不过有些地方需要注意的,不同浏览器捕获onkeypress事件时有些不一样。具体参考了下这位哥哥的博文:http://quicker.iteye.com/blog/586646

可是这keycode就和原来的不一样了怎么办呢,后来看到了这篇文章:

 

I am trying to validate textbox for numeric entry, while I added this code to accomplish in page_load event:

textbox.Attributes.Add("onkeypress""return (window.event.keyCode == 45 || window.event.keyCode == 13 || window.event.keyCode == 8 || window.event.keyCode == 9 || window.event.keyCode == 189 || window.event.keyCode == 109 || (window.event.keyCode >= 48 && window.event.keyCode <= 58) )");

It worked fine in IE7 and IE8, but it didnt work for FF though. A bit googling gave me conclusion that FF doest recognize window.event.keyCode.Basically Firefox supports the which property instead of the keyCode property IE does. By checking which (window.event.which) of them exists with an if statement we can reliably get the key that was pressed.

I replaced above code with:

textBox.Attributes.Add("onkeypress""var key; if(window.event){ key = event.keyCode;}else if(event.which){ key = event.which;} return (key == 45 || key == 13 || key == 8 || key == 9 || key == 189 || (key >= 48 && key <= 58) )");


onkeypress无法区分小键盘,所以checknum改了下

function checknum(e){

var key;

if(window.event){

key = event.keyCode;

}else{

key = e.which;

}

if((key>47 && key<58)|| key == 8){

console.log(key)

}

else{

if (e.preventDefault) {

e.preventDefault();

} else {

window.event.returnValue = false;

}

}

}

还有点问题,在ie,firefox下面可以设置input样式 ime-mode:disabled; 而其它的浏览器不支持这个样式,所以在切换语言到中文或其它语言的时候,比如搜狗拼音,输入中文拼音的时候再按shift或space键,则字母或汉字就可以出现在input里面。这时只能加一个方法了。我这里加了一个onkeyup,就替换input的值。

$("a").attachEvent("keyup",replacenum);

$("a").addEventListener("keyup",replacenum,false);

 

function replacenum(){

this.value = this.value.replace(/[^\d]/g,'');

}

本以为这样应该ok了吧,opera居然在输入中文按下shift或space时屏蔽了keyup事件。很无语啊。看来又得为opera单独弄个方法了,想来想去没找到个好方法,就用setInterval在input获得焦点时每隔50毫秒去检测input的值,然后进行替换。失去焦点时再clearInterval.

最后再给input加上onpaste="return false;"防止粘贴。

你可能感兴趣的:(onKeyDown)