I'm trying to add keyboard shortcuts on my website to make fast navigation possible using the keyboard. I'm running into a slight problem, however, with my attempted Alt+X shortcut. The event runs just fine and returns false
as it should, but the browser's File menu comes up regardless. I've also tried the preventDefault
method, but no change.
该脚本的精简版本是:
document.documentElement.onkeydown = function(e) {
e = e || window.event;
switch( e.keyCode || e.which) {
// some cases here - most notably:
case 116: // F5 key
if( activeFrame) {
activeFrame.contentWindow.location.reload();
// reloads an iframe if one is active
return false;
}
break;
// more cases...
case 88: // X key
if( e.altKey) {
// do something
return false;
}
}
}
As noted above, overriding the default action of the F5 key works just fine - the browser reloads the page only if no iframe is active. I don't quite see how to prevent the menu from appearing when Alt+X is pressed.
use stopPropagation(e);
代替preventDefault
method
function stopPropagation(e)
{
e = e || event;/* get IE event ( not passed ) */
e.stopPropagation? e.stopPropagation() : e.cancelBubble = true;
}
参考链接 http://www.webmasterworld.com/forum91/4610.htm
另一个SO问题提到了这一点防止默认 https://stackoverflow.com/questions/1000597/event-preventdefault-function-not-working-in-ie-any-helpIE 中有问题。
UPDATE
尝试使用下面的代码MSDN 参考 http://msdn.microsoft.com/en-us/library/ms536938%28v=vs.85%29.aspx
event.returnValue=false;
还有一些点来自检测击键 http://www.quirksmode.org/js/keys.html
一些一般注意事项:
- 一般来说,Mac 的可靠性不如 Windows,并且某些按键无法检测到。
- 资源管理器不会触发删除、结束、输入、转义、功能键、主页、插入、向上/向下翻页和选项卡的按键事件。
- Onkeypress,Safari 为删除、结束、功能键、home 和 pageUp.Down 提供了 63200 范围内的奇怪 keyCode 值。 onkeydown 和 -up 值正常。
- 除 Opera 外,Mac 上无法检测到 Alt、Cmd、Ctrl 和 Shift。但是,您始终可以使用 altKey、ctrlKey 和 shiftKey 属性。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)