【转】网页禁止后退键BackSpace的JavaScript实现(兼容IE、Chrome、Firefox、Opera)

 1 var forbidBackSpace = function (e) {
 2     // 获取event对象
 3     var ev = e || window.event;
 4     // 获取事件源
 5     var obj = ev.target || ev.srcElement;
 6     // 获取事件源类型
 7     var t = obj.type || obj.getAttribute('type');
 8     // 获取作为判断条件的事件类型
 9     var vReadOnly = obj.readOnly;
10     var vDisabled = obj.disabled;
11     // 处理undefined值情况 
12     vReadOnly = (vReadOnly == undefined) ? false : vReadOnly;
13     vDisabled = (vDisabled == undefined) ? true : vDisabled;
14     // 当敲Backspace键时,事件源类型为密码或单行、多行文本的, 
15     // 并且readOnly属性为true或disabled属性为true的,则退格键失效 
16     var flag1 = ev.keyCode == 8 && (t == "password" || t == "text" || t == "textarea") && (vReadOnly == true || vDisabled == true);
17     // 当敲Backspace键时,事件源类型非密码或单行、多行文本的,则退格键失效 
18     var flag2 = ev.keyCode == 8 && t != "password" && t != "text" && t != "textarea";
19     // 判断 
20     if (flag1 || flag2) { return false; }
21 }
22 
23 // 禁止后退键 作用于Firefox、Opera
24 document.onkeypress = forbidBackSpace;
25 // 禁止后退键  作用于IE、Chrome
26 document.onkeydown = forbidBackSpace;

猜你喜欢

转载自www.cnblogs.com/iflytek/p/9157690.html