Prevent BACKSPACE from navigating back with jQuery (Like Google's Homepage)

Notice while on Google's homepage, with no focus on any element, pressing BACKSPACE will put the focus into the search toolbar instead of navigating back.

How can I accomplish this?

I keep running into this problem with users in my app. They don't have focus on any element and hit BACKSPACE which throws them out of the app.


如果我们正在处理textareainput之外的退格键,我会将事件处理函数绑定到keydown并阻止该事件的默认操作:

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

I really like Andrew Whitaker's answer. It will, however, still navigate back when focused on a readonly, radio, or checkbox input field and will not allow backspace on contentEditable elements so I have added a slight modification. Credit goes to Andrew Whitaker.

$(document).on("keydown", function (e) {
    if (e.which === 8 && !$(e.target).is("input:not([readonly]):not([type=radio]):not([type=checkbox]), textarea, [contentEditable], [contentEditable=true]")) {
        e.preventDefault();
    }
});

At the moment it seems to be necessary to have every variation [contentEditable] that is in the HTML since [contentEditable] != [contentEditable=true].


The way google does this is kinda cool. When you press backspace, they focus the textfield. Preventing the users to navigate back!

You can try the same:

<script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>
<input id="target" type="text" />

<script type="text/javascript">
$(document).keydown(function(e) { if (e.keyCode == 8) $('#target').focus(); });
</script>

demo : http://jsfiddle.net/epinapala/TxG5p/

链接地址: http://www.djcxy.com/p/19382.html

上一篇: 在JavaScript中检查字符串相等性的正确方法是什么?

下一篇: 阻止BACKSPACE返回jQuery(与Google主页一样)