javascript 有没有办法在输入 type='text' 上禁用“tab”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15552974/
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
is there a way to disable 'tab' on a input type='text'?
提问by Zo72
is there a cross-browser solution to disable 'tab' on a input type='text' ?
是否有跨浏览器解决方案来禁用输入 type='text' 上的“tab”?
<input type='text' />
Pressing 'tab' moves you to the next 'focusable' component (for example a button)
按“tab”将您移动到下一个“可聚焦”组件(例如按钮)
I want instead 'tab' to do something else. For example Even in a google search tab is just used to autocomplete the suggested text instead of moving you to the next focusable component...
我想用“tab”来做其他事情。例如,即使在 google 搜索选项卡中也仅用于自动完成建议的文本,而不是将您移动到下一个可聚焦的组件...
thanks
谢谢
回答by Explosion Pills
document.querySelector('input').addEventListener('keydown', function (e) {
if (e.which == 9) {
e.preventDefault();
}
});
Depends on how cross-browser you are talking though, as the above only supports IE9 (and other modern browsers).
取决于您正在谈论的跨浏览器,因为以上仅支持 IE9(和其他现代浏览器)。
http://jsfiddle.net/ExplosionPIlls/YVUzz/
http://jsfiddle.net/ExplosionPIlls/YVUzz/
IE8- use attachEvent
instead of addEventListener
and e.keyCode
instead of e.which
, and there is no preventDefault
, but you can use return false
.
IE8- 使用attachEvent
代替addEventListener
和e.keyCode
代替e.which
,并且没有preventDefault
,但是您可以使用return false
.
回答by Mark Walters
a non jQuery implementation would be a bit like this -
非 jQuery 实现有点像这样 -
HTML would be
HTML 将是
<input type="text" id="myField1" onkeydown="return stopTab(event);" />
and JS something like below
和 JS 类似下面
function stopTab( e ) {
var evt = e || window.event
if ( evt.keyCode === 9 ) {
return false
}
}
回答by Spencer Lockhart
Yes,check if the key pressed was tab, and if so, returns false:
是的,检查按下的键是否是tab键,如果是,则返回false:
<form class='noTab'>
<input type="text" />
<input type="text" />
<select>
<option>a</option>
<option>b</option>
</select>
<textarea>
</textarea>
</form>
jQuery('.noTab').find('input,select,textarea').keydown(function (e) {
if (e.which === 9) {
return false;
}
});
jQuery will allow this work on legacy browsers.
jQuery 将允许在旧浏览器上进行这项工作。
On that fiddle it shows 2 forms, one with the class "noTab" and one without, as tab/shift+tab are useful for many forms, but not the one which has a special "tab" action.
在那个小提琴上它显示了两种形式,一种带有“noTab”类,一种没有,因为制表符/移位+制表符对许多表单都很有用,但不是具有特殊“制表符”操作的表单。