2016-09-27 96 views
0

我有我的下面的代码被用在我的一个新的web应用程序,虽然我似乎无法让它像它应该工作..我想能够加载页面,然后如果客户端点击“Tab”键,那么它只会关注其他输入字段。只有2个输入字段,这应该很容易(至少我认为:P)。无论如何,任何人都可以帮助我吗?感谢提前:)JavaScript输入焦点切换

var body = document.querySelector('body'); 

body.onkeydown = function (e) { 
    if (!e.metaKey) { 
     // e.preventDefault(); 
    } 
    if (e.code == "Tab") { 
     console.log(e.code); 
     if ($('#username').is(":focus")) { 
      $('#password').focus(); 
     } else if ($('#password').is(":focus")) { 
      $('#username').focus(); 
     } 
    } 
} 
+1

只需使用'tabindex =“1”'HTML属性来指定标签订单 – Vijai

回答

1

我假设你正在使用JQuery的,因为你在JavaScript中使用$所以我说假设下写了这个例子。我假设你希望它可以在字段中输入,而不管它们是否按Tab键,它默认为id="username" input元素。我添加了一个preventDefault来停止正常的选项卡行为。看来标签的正常行为是导致它无法正常工作的原因。希望我没有误解你,这有助于。

$("body").on("keydown", function(e) { 
 
    if (e.which !== 9 && e.keyCode !== 9) { 
 
    return; 
 
    } 
 
    console.log("Which Value:", e.which); 
 
    console.log("KeyCode Value:", e.keyCode) 
 

 
    e.preventDefault(); 
 
    if (!$('#username').is(":focus")) { 
 
    $('#username').focus(); 
 
    } else { 
 
    $('#password').focus(); 
 
    } 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<body> 
 
    <input id="username"> 
 
    <input id="password"> 
 
</body>

编辑:

如果你想做到这一点没有jQuery选择。再举一例:

var body = document.getElementsByTagName("body"); 
 

 
body[0].onkeydown = function(e) { 
 
    var username = document.getElementById("username"); 
 
    var password = document.getElementById("password"); 
 
    if (e.which !== 9 && e.keyCode !== 9 && e.code !== "Tab") { 
 
    return; 
 
    } 
 
    e.preventDefault(); 
 
    if (document.activeElement !== username) { 
 
    username.focus(); 
 
    } else { 
 
    password.focus(); 
 
    } 
 
}
<body> 
 
    <input id="username"> 
 
    <input id="password"> 
 
</body>

+0

令人惊叹!这工作!非常感谢!!! – BlackVikingPro

+0

没问题。很高兴我能帮上忙。 – zken

0

简单,使用autofocus使默认焦点到用户名,并使用tabindex移动到密码,当用户按下Tab键。

UserId :<input type="text" name="fname" autofocus tabindex="1"> 
 
Password: <input type="text" name="fname2" tabindex="2">

0

你需要e.PreventDefault()从传播和做什么打算无论如何做停止的标签事件。仅忽略Tab键的事件传播。

body.onkeydown = function (e) { 
    if (e.code == "Tab") { 
     console.log(e.code); 
     if ($('#username').is(":focus")) { 
      $('#password').focus(); 
     } else if ($('#password').is(":focus")) { 
      $('#username').focus(); 
     } 
     e.preventDefault(); 
    } 
} 

另请考虑在您的密码输入上设置type =“password”。