js取消按键事件的默认行为

来源:互联网 发布:小米6相机数据怎么清除 编辑:程序博客网 时间:2024/04/29 21:53

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>


原创粉丝点击