【问题标题】:Preventing default keystroke actions in Internet Explorer阻止 Internet Explorer 中的默认击键操作
【发布时间】:2012-11-06 18:44:52
【问题描述】:

我正在尝试在 Internet Explorer 10 中覆盖 ControlP,但似乎不知道该怎么做。我用一些非常简单的代码模拟了 Fiddle ,这些代码可以在 Chrome 中运行(至少在我的 Mac 上)。但是在 IE 10 中运行它并使用 ControlP 仍然会弹出打印对话框。

这是我的简单代码:

$('.test').on('keydown', function(e){
    if (e.metaKey || e.ctrlKey){
        $('body').append('ctrl p pressed'); 
        e.preventDefault(); 
        return false; 
    }        
});​

有人知道这里发生了什么吗?

【问题讨论】:

标签: javascript jquery internet-explorer internet-explorer-10


【解决方案1】:

为了防止默认行为

例如。 (防止 Ctrl+O 和 Ctrl+P 的默认行为)

/*jslint browser: true */
(function scriptInitScript() {
    "use strict";

    document.attachEvent("onkeydown", function handleKeyDown(event) {
        if (event.ctrlKey) {
            switch (event.keyCode) {
            case 79: // o
            case 80: // p
                event.keyCode = 0;
                return false;
            }
        }
    });

}());

JSFiddle

请注意。 jQuery 1.9 使用addEventListener(如果可用)。 See in github.

【讨论】:

  • 干得好!我以为我们已经超越了最新版本的 IE...
  • 在 IE11 document.attachEvent(...) 上不再支持,所以你必须先检查它是否可用if (document.attachEvent) { document.attachEvent(...); }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-23
  • 1970-01-01
  • 1970-01-01
  • 2019-04-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多