javascript 如何在 HTML 页面中停止 Tab 键的默认操作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24523540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to stop default action of tab key in HTML page
提问by user2800089
In my HTML page multiple components exist and on pressing tab button, focus is set to some components (not in sequence). How do I stop tab from putting focus on any component on entire page ? Using outermost div id
of html page can we block tab from putting focus on any component and on location bar as well ?
在我的 HTML 页面中存在多个组件,在按下 Tab 按钮时,焦点被设置为某些组件(不按顺序)。如何阻止选项卡将焦点放在整个页面上的任何组件上?使用div id
html 页面的最外层是否可以阻止选项卡将焦点放在任何组件和位置栏上?
I have added jsfiddle (demo)as well where even I am not using tabindex but still focus is coming so kindly tell me how to disable tab click.
我已经添加了 jsfiddle (演示),即使我没有使用 tabindex 但焦点仍然存在,所以请告诉我如何禁用选项卡单击。
$(document).on('keydown', function(event) {
if (event.keyCode == 9) { //tab pressed
event.preventDefault(); // stops its action
}
});
回答by user2800089
I tried below codeand its working fine in my scenario:
我尝试了下面的代码,它在我的场景中工作正常:
$(document).keydown(function (e)
{
var keycode1 = (e.keyCode ? e.keyCode : e.which);
if (keycode1 == 0 || keycode1 == 9) {
e.preventDefault();
e.stopPropagation();
}
});
回答by jontewks
Here is some jQuery you can use to disable the tab key on the whole page.
这里有一些 jQuery,你可以用来禁用整个页面上的 Tab 键。
$(document).on('keydown', function(event) {
if (event.keyCode == 9) { //tab pressed
event.preventDefault(); // stops its action
}
});
There may be some other ramifications of completely disabling the tab key that you may want to consider.
完全禁用您可能想要考虑的 Tab 键可能会有其他一些后果。
回答by Mohit Shrivastava
A little change try keypress
instead of keydown
and return false instead of event.preventDefault();
Something like this
一点点改变尝试keypress
而不是keydown
返回假而不是event.preventDefault();
像这样的东西
$(document).on("keypress", function(event) {
if (event.keyCode == 9) { //tab pressed
return false; // stops its action
}
});
回答by Mohit Shrivastava
I am new to this place so dont know How to answer in comments. I tried but it looks like a line not code its worked fine with this code Actually .on shud be removed from it
我是这个地方的新手,所以不知道如何在评论中回答。我试过了,但它看起来像一行不是代码,它与这段代码一起工作得很好实际上 .on 应该从中删除
$(document).keydown(function(event) {
if (event.keyCode == 9) { //tab pressed
event.preventDefault(); // stops its action
}
})
Updated the fiddleas well
更新了小提琴以及