這篇文章介紹了javascript禁制後退鍵(Backspace)實例代碼,有需要的朋友可以參考一下
復制代碼 代碼如下:
function banBackSpace(e) {
var ev = e || window.event;//獲取event對象
var obj = ev.target || ev.srcElement;//獲取事件源
var t = obj.type || obj.getAttribute('type');//獲取事件源類型
//獲取作為判斷條件的事件類型
var vReadOnly = obj.readOnly;
var vDisabled = obj.disabled;
//處理undefined值情況
vReadOnly = (vReadOnly == undefined) ? false : vReadOnly;
vDisabled = (vDisabled == undefined) ? true : vDisabled;
//當敲Backspace鍵時,事件源類型為密碼或單行、多行文本的,
//並且readOnly屬性為true或disabled屬性為true的,則退格鍵失效
var flag1 = ev.keyCode == 8 && (t == "password" || t == "text" || t == "textarea") && (vReadOnly == true || vDisabled == true);
//當敲Backspace鍵時,事件源類型非密碼或單行、多行文本的,則退格鍵失效
var flag2 = ev.keyCode == 8 && t != "password" && t != "text" && t != "textarea";
//判斷
if (flag2 || flag1) return false
}
//禁止退格鍵 作用於Firefox、Opera
document.onkeypress = banBackSpace;
//禁止退格鍵 作用於IE、Chrome
document.onkeydown = banBackSpace;