Javascript 用javascript锁定tab键?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5871626/
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-08-23 19:17:41  来源:igfitidea点击:

Lock tab key with javascript?

javascriptjquery

提问by PsyGnosis

How to lock or disable and again the tab key with javascript?

如何使用javascript锁定或禁用tab键?

回答by Naftali aka Neal

$(document).keydown(function(objEvent) {
    if (objEvent.keyCode == 9) {  //tab pressed
        objEvent.preventDefault(); // stops its action
    }
})

回答by Edgar Villegas Alvarado

You can do it like this:

你可以这样做:

$(":input, a").attr("tabindex", "-1");

That will disable getting focus with tab in all links and form elements.

这将禁止在所有链接和表单元素中使用选项卡获得焦点。

Hope this helps

希望这可以帮助

回答by Bruno Pedrosa

On Neal answer, I'd only add:

在尼尔的回答中,我只想补充:

if (objEvent.keyCode == 9) {  //tab pressed
    return;
}

Because when you finish typing CPF and press TAB, it counts as a character and changes to CNPJ mask.

因为当您完成输入 CPF 并按 TAB 时,它会被视为一个字符并更改为 CNPJ 掩码。

Complete code:

完整代码:

<script type="text/javascript">
$(document).ready(function() {
    $("#cpfcnpj").keydown(function(objEvent){
        if (objEvent.keyCode == 9) {  //tab pressed
            return;
        }
        try {
            $("#cpfcnpj").unmask();
        } catch (e) {}

        var size= $("#cpfcnpj").val().length;

        if(size < 11){
            $("#cpfcnpj").mask("999.999.999-99");
        } else {
            $("#cpfcnpj").mask("99.999.999/9999-99");
        }                   
    });
});
</script>