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

Ton*_*Jet 12 javascript jquery

我试图在所有情况下禁用订单页面上的退格按钮,除非textarea或文本输入是一个活动元素,以防止用户意外退出订单.我在大多数浏览器中都能正常工作,但在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;
            }
        }
    });
Run Code Online (Sandbox Code Playgroud)

我在这里做错了什么建议?

谢谢!

lon*_*day 25

我觉得你太复杂了.而不是检查活动元素,而是找到事件目标.这应该为您提供所需的信息.它也更好用,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();
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

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