原生js的event對象有三個鍵盤事件的值:
1) charCode: 被點擊鍵的Unicode值
2) keyCode: 被點擊鍵的ASCII十進制值
3) which: 字母數字鍵的charCode或者keyCode,具體能夠本身試試 this
Mootools的event被封裝後,統一成爲code和key:code
event.code = event.which || event.keyCode; event.key = String.fromCharCode(code).toLowerCase();
寫了個方法,用於控制數字輸入對象
// 價格字符串格式(小數點後最多兩位) $$('.jsForPrice').addEvents({ 'keypress': function(ev){ var result; if(this.val().length === 0 || this.val().test('\\.')){// 只能有1個點號 result = ev.code>=48&&ev.code<=57 || ev.code==8; }else{ result = ev.code>=48&&ev.code<=57||ev.code==8||ev.code==46; } return result; }, 'keyup': function(ev){ if(this.val().test('\\.')){ if(this.val().split('.')[1].length>2){ this.val(this.val().substring(0, this.val().length-1)) } } //console.log(this.val().test('^[0-9]+(\\.[0-9]{1,2}){0,1}$')) } });
參考:stackoverflow事件