在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。

编辑2:我不是想阻止历史航行,只是想阻止事故。

EDIT3: @brentonstrines评论(因为这个问题太受欢迎了,所以移到这里):这是一个长期的“修复”,但你可以支持Chromium bug来改变webkit中的这种行为


当前回答

到目前为止给出的所有答案都集中在将修复脚本编写到web页面上,但是如果我只是想为自己使用该功能,而不影响其他用户呢?

In this case a solution for the browser itself is to be preferred: - Firefox on Linux "unmapped" the backspace behavior since 2006 so it's not affected; (at any rate, it was simply set to scroll up before then) - Chrome has just announced that it will do the same from now on; (http://forums.theregister.co.uk/forum/1/2016/05/20/chrome_deletes_backspace/) - Firefox on Windows can be set to ignore backspace by going into about:config and changing the backspace_action setting to 2; (http://kb.mozillazine.org/Browser.backspace_action) - Safari ?!

其他回答

以下是我对得票最多的答案的改写。我试着检查element.value!==undefined(因为有些元素可能没有HTML属性,但可能在原型链的某个地方有javascript值属性),然而这并不是很好,并且有很多边缘情况。似乎没有一个很好的方法来证明这一点,所以白名单似乎是最好的选择。

这将在事件气泡阶段的末尾注册元素,因此如果您想以任何自定义方式处理Backspace,您可以在其他处理程序中这样做。

这也检查instanceof HTMLTextAreElement,因为理论上可以有一个继承自它的web组件。

这不会检查contentEditable(与其他答案结合)。

https://jsfiddle.net/af2cfjc5/15/

var _INPUTTYPE_WHITELIST = ['text', 'password', 'search', 'email', 'number', 'date'];

function backspaceWouldBeOkay(elem) {
    // returns true if backspace is captured by the element
    var isFrozen = elem.readOnly || elem.disabled;
    if (isFrozen) // a frozen field has no default which would shadow the shitty one
        return false;
    else {
        var tagName = elem.tagName.toLowerCase();
        if (elem instanceof HTMLTextAreaElement) // allow textareas
            return true;
        if (tagName=='input') { // allow only whitelisted input types
            var inputType = elem.type.toLowerCase();
            if (_INPUTTYPE_WHITELIST.includes(inputType))
                return true;
        }   
        return false; // everything else is bad
    }
}

document.body.addEventListener('keydown', ev => {
    if (ev.keyCode==8 && !backspaceWouldBeOkay(ev.target)) {
        //console.log('preventing backspace navigation');
        ev.preventDefault();
    }
}, true); // end of event bubble phase

为我工作

<script type="text/javascript">


 if (typeof window.event != 'undefined')
    document.onkeydown = function()
    {
        if (event.srcElement.tagName.toUpperCase() != 'INPUT')
            return (event.keyCode != 8);
    }
else
    document.onkeypress = function(e)
    {
        if (e.target.nodeName.toUpperCase() != 'INPUT')
            return (e.keyCode != 8);
    }

</script>

这段代码解决了所有浏览器的问题:

onKeydown:function(e)
{
    if (e.keyCode == 8) 
    {
      var d = e.srcElement || e.target;
      if (!((d.tagName.toUpperCase() == 'BODY') || (d.tagName.toUpperCase() == 'HTML'))) 
      {
         doPrevent = false;
      }
       else
      {
         doPrevent = true;
      }
    }
    else
    {
       doPrevent = false;
    }
      if (doPrevent)
      {
         e.preventDefault();
       }

  }

JavaScript - jQuery方式:

$(document).on("keydown", function (e) {
    if (e.which === 8 && !$(e.target).is("input, textarea")) {
        e.preventDefault();
    }
});

Javascript -本地的方式,这为我工作:

<script type="text/javascript">

//on backspace down + optional callback
function onBackspace(e, callback){
    var key;
    if(typeof e.keyIdentifier !== "undefined"){
        key = e.keyIdentifier;

    }else if(typeof e.keyCode !== "undefined"){
        key = e.keyCode;
    }
    if (key === 'U+0008' || 
        key === 'Backspace' || 
        key === 8) {
                    if(typeof callback === "function"){
                callback();
            }
            return true;
        }
    return false;
}

//event listener
window.addEventListener('keydown', function (e) {

    switch(e.target.tagName.toLowerCase()){
        case "input":
        case "textarea":
        break;
        case "body":
            onBackspace(e,function(){
                e.preventDefault();
            });

        break;
    }
}, true);
</script>

到目前为止给出的所有答案都集中在将修复脚本编写到web页面上,但是如果我只是想为自己使用该功能,而不影响其他用户呢?

In this case a solution for the browser itself is to be preferred: - Firefox on Linux "unmapped" the backspace behavior since 2006 so it's not affected; (at any rate, it was simply set to scroll up before then) - Chrome has just announced that it will do the same from now on; (http://forums.theregister.co.uk/forum/1/2016/05/20/chrome_deletes_backspace/) - Firefox on Windows can be set to ignore backspace by going into about:config and changing the backspace_action setting to 2; (http://kb.mozillazine.org/Browser.backspace_action) - Safari ?!