This time I will bring you js to disable browser back events. What are the precautions for js to disable browser back events? The following is a practical case, let’s take a look.
In the project, I encountered the problem of pressing the Backspace key to make the browser go back. I searched for several solutions on the Internet, but none of them were ideal. So we gathered everyone’s wisdom and learned from the strengths of many families, and summarized it as follows: 1. Define the method to prevent Backspace in public jsfunction banBackSpace(e){ var ev = e || window.event; //各种浏览器下获取事件对象 var obj = ev.relatedTarget || ev.srcElement || ev.target ||ev.currentTarget; //按下Backspace键 if(ev.keyCode == 8){ var tagName = obj.nodeName //标签名称 //如果标签不是input或者textarea则阻止Backspace if(tagName!='INPUT' && tagName!='TEXTAREA'){ return stopIt(ev); } var tagType = obj.type.toUpperCase();//标签类型 //input标签除了下面几种类型,全部阻止Backspace if(tagName=='INPUT' && (tagType!='TEXT' && tagType!='TEXTAREA' && tagType!='PASSWORD')){ return stopIt(ev); } //input或者textarea输入框如果不可编辑则阻止Backspace if((tagName=='INPUT' || tagName=='TEXTAREA') && (obj.readOnly==true || obj.disabled ==true)){ return stopIt(ev); } } } function stopIt(ev){ if(ev.preventDefault ){ //preventDefault()方法阻止元素发生默认的行为 ev.preventDefault(); } if(ev.returnValue){ //IE浏览器下用window.event.returnValue = false;实现阻止元素发生默认的行为 ev.returnValue = false; } return false; }
$(function(){ //实现对字符码的截获,keypress中屏蔽了这些功能按键 document.onkeypress = banBackSpace; //对功能按键的获取 document.onkeydown = banBackSpace; })
JS home page news sliding effect
JS click cycle to switch to play pictures
The above is the detailed content of js prohibits browser back event. For more information, please follow other related articles on the PHP Chinese website!