标签:
最近在看javascript高级程序设计这本书,通过写一些demo帮助加深理解记忆。
此输入数字的文本框在用输入法输入字符的时候还有bug
1 <!DOCTYPE html> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <title></title> 5 <script type="text/javascript"> 6 var EventUtil = { 7 addHander: function (element, type, hander) { 8 if (element.addEventListener) { //DOM2 9 element.addEventListener(type, hander, false); //在冒泡阶段调用事件处理程序 10 } else if (element.attachEvent) { //IE 11 element.attachEvent("on" + type, hander); 12 } else { 13 element["on" + type] = hander; 14 } 15 }, 16 removeHander: function (element, type, hander) { 17 if (element.removeEventListener) { 18 element.removeEventListener(type, hander, false); 19 } else if (element.detachEvent) { 20 element.detachEvent("on" + type, hander); 21 } else { 22 element["on" + type] = null; 23 } 24 }, 25 getEvent: function (event) { 26 return event ? event : window.event; 27 }, 28 getTarget: function (event) { 29 return event.target || event.srcElement; 30 }, 31 preventDefault: function (event) { 32 if (event.preventDefault) { 33 event.preventDefault(); 34 } else { 35 event.returnValue = false; 36 } 37 }, 38 stopPropagation: function (event) { 39 if (event.stopPropagation) { 40 event.stopPropagation(); 41 } else { 42 event.cancelBubble = true; 43 } 44 }, 45 getCharCode: function (event) { 46 if (typeof event.charCode == "number") { 47 return event.charCode; //ASCII编码 48 } else { 49 return event.keyCode; //IE8及以前 Opera 50 } 51 }, 52 getClipboardText: function (event) { 53 var clipboardData = (event.clipboardData || window.clipboardData); 54 return clipboardData.getData("text"); 55 }, 56 setClipboardText: function (event, value) { 57 if (event.clipboardData) { 58 return event.clipboardData.setData("text/plian", value); 59 } else if (window.clipboardData) { //IE 60 return window.clipboardData.setData("text", value); 61 } 62 } 63 }; 64 65 66 </script> 67 </head> 68 <body> 69 <input type="text" id="mynum" /> 70 <script type="text/javascript"> 71 var mynum = document.getElementById("mynum"); 72 //键盘输入 73 EventUtil.addHander(mynum, "keypress", function (event) { 74 event = EventUtil.getEvent(event); 75 var charCode = EventUtil.getCharCode(event); 76 if (!/\d/.test(String.fromCharCode(charCode)) 77 && charCode > 8 //不屏蔽向上键,向下键,退格键,删除键;这些键都会触发keypress事件;这些键对应的字符编码小于9 78 && !event.ctrlKey //不屏蔽ctrl键,能复制,粘贴 79 ) 80 { 81 EventUtil.preventDefault(event); 82 } 83 }); 84 //剪贴板操作 85 EventUtil.addHander(mynum, "paste", function (event) { 86 event = EventUtil.getEvent(event); 87 var text = EventUtil.getClipboardText(event); 88 if (!/^\d*$/.test(text)) { 89 EventUtil.preventDefault(event); 90 } 91 }); 92 </script> 93 </body> 94 </html>
标签:
原文地址:http://www.cnblogs.com/biganqiang/p/4304442.html