Home >Web Front-end >JS Tutorial >How to disable the Backspace key in JavaScript

How to disable the Backspace key in JavaScript

PHPz
PHPzOriginal
2016-05-16 15:27:571476browse

Today I discovered in IE browser that when setting the text box to read-only using the readonly="readonly" attribute there is a strange problem: if the cursor enters the read-only text box and then press Pressing the Backspace key will jump to the previous page. The effect is just like clicking the browser's back button to return to the previous page. However, there is no such problem under Firefox and Google. In order to solve this problem, I wrote the following The processing method, if the text box is read-only, then disable the Backspace key.
The code is as follows:

//处理键盘事件 禁止后退键(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.getAttribute('readonly');
  //处理null值情况
  vReadOnly = (vReadOnly == "") ? false : vReadOnly;
  //当敲Backspace键时,事件源类型为密码或单行、多行文本的,
  //并且readonly属性为true或enabled属性为false的,则退格键失效
  var flag1=(ev.keyCode == 8 && (t=="password" || t=="text" || t=="textarea") 
     && vReadOnly=="readonly")?true:false;
  //当敲Backspace键时,事件源类型非密码或单行、多行文本的,则退格键失效
  var flag2=(ev.keyCode == 8 && t != "password" && t != "text" && t != "textarea")
     ?true:false;  
  
  //判断
  if(flag2){
   return false;
  }
  if(flag1){ 
   return false; 
  } 
 }

window.onload=function(){
 //禁止后退键 作用于Firefox、Opera
 document.onkeypress=banBackSpace;
 //禁止后退键 作用于IE、Chrome
 document.onkeydown=banBackSpace;
}

After adding this processing, you can easily solve the problem of "pressing the Backspace key in the read-only input box under IE" Go back to the previous page" problem.

I hope you like this article and continue to pay attention to the articles updated by the editor.

【Recommended related tutorials】

1. JavaScript video tutorial
2. JavaScript online manual
3. bootstrap tutorial

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn