如何在所有浏览器上禁用退格键按键? [英] How can I disabling backspace key press on all browsers?

查看:677
本文介绍了如何在所有浏览器上禁用退格键按键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to disable the backspace button on an order page in all cases except when a textarea or text input is an active element to prevent users from accidentally backing out of an order. I have it working fine in most browsers, but in IE (testing in IE9, both regular and compatibility mode) it still allows the user to hit the backspace and go to the previous page.

以下是代码:

$(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;
            }
        }
    });

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

Any advice on what I'm doing wrong here?

谢谢!

推荐答案

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

I think you're overcomplicating that. Rather than checking for an active element, find the event target instead. This should give you the information you need. It's also better to use keydown rather than keypress when there is no visible character. Finally, it's better to use e.preventDefault() for better granularity.

$(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();
        }
    }
});

NB我可以反过来这样做,而不是空如果阻止并且所有代码都在 else 块中,但我认为这更具可读性。

NB I could have done this the other way round, rather than an empty if block and all the code going in the else block, but I think this is more readable.

这篇关于如何在所有浏览器上禁用退格键按键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆