如何在所有浏览器上禁用退格键?

新手上路,请多包涵

我试图在所有情况下禁用订单页面上的退格按钮,除非文本区域或文本输入是活动元素,以防止用户意外退出订单。我让它在大多数浏览器中工作正常,但在 IE 中(在 IE9 中测试,常规模式和兼容模式)它仍然允许用户点击退格键并转到上一页。

这是代码:

 $(document).keypress(function(e){
        var activeNodeName=document.activeElement.nodeName;
        var activeElType=document.activeElement.type;
        if (e.keyCode==8 && activeNodeName != 'INPUT' && activeNodeName != 'TEXTAREA'){
            return false;
        } else {
            if (e.keyCode==8 && activeNodeName=='INPUT' && activeElType != 'TEXT' && activeElType != 'text'){
                return false;
            }
        }
    });

关于我在这里做错了什么的任何建议?

谢谢!

原文由 TonyTheJet 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 407
2 个回答

我认为你过于复杂了。与其检查活动元素,不如查找事件目标。这应该为您提供所需的信息。当没有可见字符时,最好使用 keydown 而不是 keypress 。最后,最好使用 e.preventDefault() 以获得更好的粒度。

 $(document).keydown(function(e) {
    var nodeName = e.target.nodeName.toLowerCase();

    if (e.which === 8) {
        if ((nodeName === 'input' && e.target.type === 'text') ||
            nodeName === 'textarea') {
            // do nothing
        } else {
            e.preventDefault();
        }
    }
});

注意,我本可以反过来做,而不是一个空的 if 块和 else 块中的所有代码,但我认为这更具可读性。

原文由 lonesomeday 发布,翻译遵循 CC BY-SA 3.0 许可协议

大多数示例似乎都是针对 JQuery 框架的——这里是 ExtJS 的示例

(我最近收到了很多反对票,因为这个问题现在有 JQuery 标签,以前没有。如果你喜欢我可以删除答案,因为 JQuery 不是这样,但事实证明它可以帮助其他人不使用该框架)。

要使用此功能,请将此代码块添加到您的代码库中,我建议将其添加到应用程序初始化函数 () 中。

     /**
     * This disables the backspace key in all browsers by listening for it on the keydown press and completely
     * preventing any actions if it is not which the event fired from is one of the extjs nodes that it should affect
     */
    Ext.EventManager.on(window, 'keydown', function(e, t) {
       var nodeName = e.target.nodeName.toLowerCase();
        if (e.getKey() == e.BACKSPACE) {
            if ((nodeName === 'input' && e.target.type === 'text') ||
                nodeName === 'textarea') {
                // do nothing
            } else {
                e.preventDefault();
            }
        }
    });

原文由 James Nurse 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题