【问题标题】:Ctrl+w event captured in firefox not working in other browsersFirefox 中捕获的 Ctrl+w 事件在其他浏览器中不起作用
【发布时间】:2014-03-10 07:02:55
【问题描述】:

我有下面的代码,通过它我得到浏览器的 Ctrl+w 事件,但它只在 Firefox 中有效,在其他浏览器中无效。我发现keydown/keypress有问题。有没有办法为这两个事件(keydown/keypress)编写浏览器兼容性代码。

这是我的代码:

$(window).keydown(function (event) {
    event.preventDefault();
    if (event.which == 119 && event.ctrlKey) {
        alert("Ctrl-W pressed");
    }
    return false;
});

【问题讨论】:

    标签: jquery internet-explorer google-chrome firefox


    【解决方案1】:

    使用 keypress 代替 keydown:demo

    $(window).keypress(function(event) {
            event.preventDefault();
    
            if (event.which == 119 && event.ctrlKey) {
                alert("Ctrl-W pressed");
            }    
    
        return false;
    });
    

    【讨论】:

    • 它在 chrome 和 IE 中不起作用。我希望这段代码可以在所有浏览器中运行。
    • 在 chrome 中不可能,你不能用 js 覆盖浏览器行为 :)
    【解决方案2】:

    这里是仅针对未设置默认键的解决方案

    另外你不能使用 JS 覆盖浏览器的默认行为

    这里是快速解决方案

    解决方案 1(快速)

    代码

    $(document).keypress("w",function(e) {
      if(e.ctrlKey)
        alert("Ctrl+C was pressed!!");
    });
    

    小提琴 http://jsfiddle.net/J4t5d/1/

    解决方案 2

    你可以使用 js 库轻松做到这一点 shortcut.js

    解决方案 3

    你可以这样做:)

    $(window).keydown(function(event) {event.preventDefault();
        if (event.which == 87 && ctrlMode == true) {
            alert("Ctrl-W pressed");
        }    
         return false;
    });
    $(document).keydown(function(e){e.preventDefault();
     if(e.ctrlKey){
            ctrlMode = true;
     }
    });
    $(document).keyup(function(e){e.preventDefault();
     if(e.ctrlKey){
         ctrlMode = false;
     }
    });
    

    小提琴http://jsfiddle.net/J4t5d/5/

    希望对你有帮助:)

    【讨论】:

    • 它不工作。我希望这段代码可以在所有浏览器中运行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 2011-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多