導語:日常開發中,網站需求是用戶點擊瀏覽器的返回事件,網站會執行某些操作。
先來看看效果:

代碼一:
1 $(function(){ 2 3 pushHistory(); 4 5 window.addEventListener("popstate", function(e) { 6 7 alert("監聽到返回按鈕事件啦"); 8 9 //根據自己的需求實現自己的功能 10 11 //window.location.href = 'https://www.baidu.com' 12 13 },false); 14 15 function pushHistory() { 16 17 var state = { 18 19 title:"title", 20 21 url:"#" 22 23 }; 24 25 window.history.pushState(state,"title","#"); 26 27 } 28 29 });
代碼二:
1 $(document).ready(function (e) { 2 3 var counter =0; 4 5 if (window.history && window.history.pushState) { 6 7 $(window).on('popstate', function () { 8 9 window.history.pushState('forward',null,'#'); 10 11 window.history.forward(1); 12 13 // alert("不可回退"); //如果需在彈框就有它 14 15 self.location="orderinfo.html";//如查需要跳轉頁面就用它 16 17 }); 18 19 } 20 21 window.history.pushState('forward',null,'#');//在IE中必須得有這兩行 22 23 window.history.forward(1); 24 25 });