//处理键盘事件 禁止后退键(Backspace)密码或单行、多行文本框/div除外
function banBackSpace(e) {
var ev = e || window.event; //获取event对象
var obj = ev.target || ev.srcElement; //获取事件源
var t = obj.type || obj.getAttribute('type') || obj.tagName; //获取事件源类型
//获取作为判断条件的事件类型
var vReadOnly = obj.getAttribute('readonly');
var vEnabled = obj.getAttribute('enabled');
var con = obj.getAttribute('contenteditable');
//处理null值情况
vReadOnly = (vReadOnly == null) ? false : vReadOnly;
vEnabled = (vEnabled == null) ? true : vEnabled;
con = (con == null) ? false : con;
//当敲Backspace键时,事件源类型为密码或单行、多行文本的,
//并且readonly属性为true或contenteditable属性为ture或enabled属性为false的,则退格键失效
var flag1 = (ev.keyCode == 8 && (t == "DIV" || t == "text" || t == "textarea") &&
(vReadOnly == true || vEnabled != true || con == true)) ? true : false;
//当敲Backspace键时,事件源类型非div或单行、多行文本的,则退格键失效
var flag2 = (ev.keyCode == 8 && t != "DIV" && t != "text" && t != "textarea") ?
true : false;
//判断
if(flag2) {
return false;
}
if(flag1) {
return false;
}
}
//google浏览器使用
document.onkeydown=banBackSpace;
之前在网上找到的办法和代码,但是测试过程中发现问题,发现获取的t为null,后又将t更改为
var t = obj.type || obj.getAttribute('type') || obj.tagName; //获取事件源类型
后又增加了对可编辑DIV的支持
var con = obj.getAttribute('contenteditable');