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」。