在 IE 上,我可以使用(非常非标准但有效的)jQuery 来做到这一点
if ($.browser.msie)
$(document).keydown(function(e) { if (e.keyCode == 8) window.event.keyCode = 0;});
但是是否有可能以适用于 Firefox 的方式进行,或者以跨浏览器的方式进行以获得奖励?
记录在案:
$(document).keydown(function(e) { if (e.keyCode == 8) e.stopPropagation(); });
什么都不做。
$(document).keydown(function(e) { if (e.keyCode == 8) e.preventDefault(); });
解决了这个问题,但是让退格键在页面上无法使用,这比原来的行为还要糟糕。
编辑: 我这样做的原因是我不是在创建一个简单的网页,而是一个大型应用程序。仅仅因为你在错误的地方按了退格键就失去了 10 分钟的工作时间,这是非常令人讨厌的。通过防止退格键向后导航,防止错误与烦人用户的比率应远高于 1000/1。
EDIT2:我不是试图阻止历史导航,只是意外。
EDIT3:@brentonstrines 评论(因为这个问题很受欢迎,所以移到这里):这是一个长期的“修复”,但你可以支持 Chromium bug to change this behavior in webkit
最佳答案
这段代码解决了这个问题,至少在 IE 和 Firefox 中是这样(没有测试任何其他的,但如果问题在其他浏览器中存在,我给它一个合理的工作机会)。
// 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;
}
}
});
关于javascript - 如何防止退格键向后导航?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1495219/