[英]How not to lose focus on a login page
我有一個簡單的登錄表單,其中包含2個輸入字段:“username”和“password”。 “用戶名”字段默認為焦點。 問題是,當用戶點擊“用戶名”或“密碼”字段外,焦點消失了(既不是“用戶名”也不是“密碼”字段“)。如何強調焦點在這兩個字段上?只要 ?
在我的情況下,這是一個非常討厭的行為,所以我真的想這樣做:)
我可以這樣做:
$("*").focus(function() {
if (!$(this).hasClass("my_inputs_class")) {
// How to stop the focusing process here ?
}
});
?
聽起來你總是希望你的一個投入能夠集中,公平。 我這樣做的方法是綁定你的每個輸入blur()
事件,這樣如果它發生,它將轉到下一個元素。
這是標記:
<body>
<form method="POST" action=".">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" name="submit" />
</form>
</body>
這是jQuery:
$(document).ready(function() {
// what are the named fields the user may focus on?
var allowed = ['username', 'password', 'submit'];
$.each(allowed, function(i, val) {
var next = (i + 1) % allowed.length;
$('input[name='+val+']').bind('blur', function(){
$('input[name='+allowed[next]+']').focus();
});
});
$('input[name='+allowed[0]+']').focus();
});
你可以使用javascript來集中注意焦點,但你真的不應該 。 強制關注這些字段會破壞頁面的正常交互。 這意味着用戶無法像點擊頁面上的鏈接那樣簡單,因為焦點總是在那些輸入上。
請不要這樣做:)
如果你真的想要這樣做(你不應該)使用delegate()而不是在每個HTML元素上設置一個單獨的事件處理程序:
$('body').delegate('*', 'focus', function() {
if (!$(this).hasClass("my_inputs_class")) {
$('#username').focus();
return false;
}
});
但是考慮到這將通過鍵盤導航(包括提交按鈕,頁面上的任何鏈接等)使除了兩個輸入字段之外的所有元素無法實現。
設置blur
事件處理程序,使其將焦點恢復到您的一個輸入。
你可以這樣做(在偽代碼中):
if user || pass blured
if user.len > 0
pass.setFocus
else
user.setFocus
希望你明白。
在body
元素(或覆蓋大部分頁面的div)上安裝onClick
處理程序。 然后單擊div應該將焦點設置在用戶名/密碼字段上。
我也建議綁定在“用戶名” 返回 “將焦點設置密碼”按鈕, 返回在“密碼”字段設置為“提交表單”。
您可以在最小時間間隔后重新關注輸入,從而啟用對鏈接的點擊。
每次對象獲得焦點時,檢查它是否具有所需的類:如果沒有將焦點設置為第一個表單輸入; 這條路:
<html>
<head>
<title>Example</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js" />
<script type="text/javascript" >
$(function() {
$('*').focus(function() { var obj = this; setTimeout(function () {checkFocus(obj)}, 1)});
})
function checkFocus(obj) {
if (!$(obj).hasClass('force_focus')){
$('input.force_focus:first').focus()
}
}
</script>
</head>
<body>
<a href="http://www.google.com">Extrnal link</a>
<form><div>
User: <input type="text" name="user" class="force_focus"/><br/>
Password: <input type="password" name="password" class="force_focus"/><br/>
Other: <input type="text" name="other" class=""/><br/>
<input type="submit" name="submit" value="Login" />
</div></form>
</body>
</html>
這只是一個想法,您可以使用setInterval函數將焦點放在用戶名字段中,並且可以在需要時使用clearInterval函數中斷它。
var A = setInterval(function(){ $('#username').focus();}, 100);
......為了讓它變通,你可以做這樣的事情
$('#password').focus(function(){ clearInterval(A);});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.