阻止BACKSPACE使用jQuery导航(如Google的主页)

Fas*_*ack 39 javascript jquery

请注意,在Google的主页上,不关注任何元素,按BACKSPACE会将焦点放入搜索工具栏而不是向后导航.

我怎么能做到这一点?

我的应用程序中的用户一直遇到此问题.他们没有专注于任何元素,并点击BACKSPACE将其抛出应用程序.

And*_*ker 64

我会绑定一个事件处理程序,keydown并阻止该事件的默认操作,如果我们正在处理a textarea或以外的退格键input:

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

  • 有人:我选择了这个答案,因为它会一直阻止BACKSPACE,除非焦点在`input`或`textarea`上. (2认同)

J.M*_*ney 23

我真的很喜欢Andrew Whitaker的回答.但是,当专注于只读,无线电或复选框输入字段时,它仍然会导航回来,并且不允许在contentEditable元素上退格,所以我添加了一些修改.归功于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();
    }
});
Run Code Online (Sandbox Code Playgroud)

目前,似乎有必要在[contentEditable]!= [contentEditable = true]中包含HTML中的每个变体[contentEditable].


Esw*_*ala 11

谷歌这样做的方式有点酷.当您按退格键时,它们会聚焦文本字段,从而阻止用户返回!

你可以尝试相同:

<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>
Run Code Online (Sandbox Code Playgroud)

演示:http://jsfiddle.net/epinapala/TxG5p/

  • 虽然这适用于1个输入字段,而Google主页只有一个输入字段,但它不能用于输入多于1的页面,因为删除文本会导致字段将焦点切换到#target.这就是为什么Andrew Whitaker的答案是更好的解决方案. (2认同)