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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:10:28  来源:igfitidea点击:

is there a way to disable 'tab' on a input type='text'?

javascriptjqueryhtmlfocus

提问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 attachEventinstead of addEventListenerand e.keyCodeinstead of e.which, and there is no preventDefault, but you can use return false.

IE8- 使用attachEvent代替addEventListenere.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 将允许在旧浏览器上进行这项工作。

http://jsfiddle.net/JxMhY/

http://jsfiddle.net/JxMhY/

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”类,一种没有,因为制表符/移位+制表符对许多表单都很有用,但不是具有特殊“制表符”操作的表单。