<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>jstest</title> <link rel="stylesheet" type="text/css" href="style.css"/> <script type="text/javascript" src="base.js"></script> <script type="text/javascript" src="js.js"></script> </head> <body> <form id="myForm" name="yourForm"> 姓名:<input type="text" name="user" value="text" /><br /> <textarea name="content" rows="" cols="" style="width: 200px;">dsfsafsdafdsafdf dsfsd</textarea> </form> </body> </html>
base.js
//跨浏览器添加事件 function addEvent(obj,type,fn){ if(obj.addEventListener){ obj.addEventListener(type,fn,false); }else if(obj.attachEvent){ obj.attachEvent('on'+type,fn); } } //跨浏览器移除事件 function removeEvent(obj,type,fn){ if(obj.removeEventListener){ obj.removeEventListener(obj,fn,false); }else if(obj.detachEvent){ obj.detach('on'+type,fn); } } //跨浏览器获取目标对象 function getTarget(evt){ if(evt.target){ //w3c return evt.target; }else if(window.event.srcElement){ return window.event.srcElement; } } //跨浏览器阻止默认行为 function preDef(evt){ var e = evt || window.event; if(e.preventDefault){ e.preventDefault(); }else{ e.returnValue = false; } } //跨浏览器获取字符编码 function getCharCode(evt){ var e = evt || window.event; if(typeof e.charCode == "number"){ return e.charCode; }else{ return e.keyCode; } }
js.js
addEvent(window,'load',function(){ var fm = document.forms['yourForm']; var user = fm.elements['user']; var content = fm.elements['content']; /* //屏蔽非数字键的输入 addEvent(content,'keypress',function(evt){ var e = evt || window.event; var charCode = getCharCode(evt); if(!/\d/.test(String.fromCharCode(charCode)) && charCode > 0){ preDef(evt); } console.log(e.charCode); }); addEvent(content,'copy',function(evt){ preDef(evt); }); addEvent(content,'cut',function(evt){ preDef(evt); }); addEvent(content,'paste',function(evt){ preDef(evt); }); //屏蔽输入法用户体验不好 //content.style.imeMode = 'disabled'; */ //验证数据非法后取消输入 addEvent(content,'keyup',function(evt){ this.value = this.value.replace(/[^\d]/g,''); //将非数字键转换为空 }); });