JavaScript:非输入框禁用退格键

在js文件或<javascript>标签中加入如下代码:

 1 /**
 2 *非输入框禁用退格键
 3 */
 4 function banBackspace(e) 
 5 {
 6     var ev = e || window.event;
 7     var field = ev.target || ev.srcElement;
 8     var fieldType = field.type || field.getAttribute('type');
 9     var isReadOnly = field.readOnly;
10     var isDisabled = field.disabled;
11     isReadOnly = (isReadOnly == undefined) ? false : isReadOnly;
12     isDisabled = (isDisabled == undefined) ? true : isDisabled;
13    
14     var KEY_BACKSPACE = 8;
15     var inputFieldTypes = [ 'password', 'text' , 'textarea'];
16    
17     var isOnReadonlyOrDisabledField = inputFieldTypes.containsArr(fieldType) && (isReadOnly || isDisabled);
18     var isNotOnAnyField = !inputFieldTypes.containsArr(fieldType);
19    
20     if (ev.keyCode == KEY_BACKSPACE && (isOnReadonlyOrDisabledField || isNotOnAnyField)) {
21          return false ;
22     }
23 }
24 document.onkeydown = banBackspace;

 

posted @ 2016-11-15 19:40  一碗豆浆  阅读(291)  评论(0编辑  收藏  举报