如何防止退格键向后浏览? [英] How can I prevent the backspace key from navigating back?

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

问题描述

在IE上,我可以用(非常非标准,但工作)jQuery做到这一点

On IE I can do this with the (terribly non-standard, but working) jQuery

if ($.browser.msie)
    $(document).keydown(function(e) { if (e.keyCode == 8) window.event.keyCode = 0;});

但是可以用一种在Firefox上工作的方式,或者以跨浏览器方式

But is it possible to do in a way which works on Firefox, or in a cross-browser way for a bonus?

对于记录:

$(document).keydown(function(e) { if (e.keyCode == 8) e.stopPropagation(); });

不执行任何操作。

$(document).keydown(function(e) { if (e.keyCode == 8) e.preventDefault(); });

解决了问题,但是退格键在页面上不可用,行为。

solves the problem, but renders the backspace key unusable on the page, which is even worse than the original behaviour.

编辑:
我这样做的原因是我不是创建一个简单的网页,而是一个大的应用程序。这是令人难以置信的烦恼,失去10分钟的工作,只是因为你按下退格在错误的地方。

The reason I do this is that I'm not creating a simple web page but a large application. It is incredibly annoying to lose 10 minutes of work just because you pressed backspace in the wrong place. The ratio of preventing mistakes vs. annoying users should be way above 1000/1 by preventing the backspace key from navigating back.

EDIT2:我不是

I'm not trying to prevent history navigation, just accidents.

EDIT3:@brentonstrines评论(移动到这里,因为问题是如此受欢迎):这是一个长期的修复,但您可以将您的支持放在 Chromium错误后更改此webkit中的行为

@brentonstrines comment (moved here since the question is so popular): This is a long-term 'fix', but you could throw your support behind the Chromium bug to change this behavior in webkit

推荐答案

此代码解决了这个问题,至少在IE和Firefox

This code solves the problem, at least in IE and Firefox (haven't tested any other, but I give it a reasonable chance of working if the problem even exists in other browsers).

// Prevent the backspace key from navigating back.
$(document).unbind('keydown').bind('keydown', function (event) {
    if (event.keyCode === 8) {
        var doPrevent = true;
        var types = ["text", "password", "file", "search", "email", "number", "date", "color", "datetime", "datetime-local", "month", "range", "search", "tel", "time", "url", "week"];
        var d = $(event.srcElement || event.target);
        var disabled = d.prop("readonly") || d.prop("disabled");
        if (!disabled) {
            if (d[0].isContentEditable) {
                doPrevent = false;
            } else if (d.is("input")) {
                var type = d.attr("type");
                if (type) {
                    type = type.toLowerCase();
                }
                if (types.indexOf(type) > -1) {
                    doPrevent = false;
                }
            } else if (d.is("textarea")) {
                doPrevent = false;
            }
        }
        if (doPrevent) {
            event.preventDefault();
            return false;
        }
    }
});

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

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