js取消按鍵事件的預設行為
阿新 • • 發佈:2019-02-02
event.preventDefault()方法是用於取消事件的預設行為,但此方法並不被ie支援,在ie下需要用window.event.returnValue。下面是demo程式碼,直接拷貝放到一個檔案可以執行,如按下bakcspace鍵可以返回上次訪問網頁,把12行//stopDefault(e);程式碼開啟後試試還能不能返回。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>test</title> </head> <script> document.onkeydown = keydownEvent; function keydownEvent(e) { var keycode = e.which || e.keyCode; //stopDefault(e); switch (keycode) { case 13: break; default: break; } } function stopDefault(e) { if (e&&e.preventDefault) { e.preventDefault(); } else { window.event.returnValue = false; } } </script> <body> </body> </html>