.focus()
.focus( handler(eventObject) ) 返回: jQuery
描述: 為 "focus" 事件綁定一個處理函數,或者觸發(fā)元素上的 "focus" 事件。
-
version added: 1.0.focus( handler(eventObject) )
handler(eventObject)每次事件觸發(fā)時會執(zhí)行的函數。
-
version added: 1.4.3.focus( [ eventData ], handler(eventObject) )
eventData將要傳遞給事件處理函數的數據映射。
handler(eventObject)每次事件觸發(fā)時會執(zhí)行的函數。
version added: 1.0.focus()
- 這個函數的第一種用法是
.bind('focus', handler)
的快捷方式,第二種用法是.trigger('focus')
的快捷方式。 - 該
focus
事件被發(fā)送到一個獲得焦點時的元素。此事件隱式適用于有限的元素,比如表單元素(<input>
,<select>
等)和鏈接元素(<a href>
)。在最近版本的瀏覽器中,該事件可以擴展到所有包括通過顯式設置tabindex
屬性的元素類型。一個元素可以通過鍵盤命令獲得焦點,如Tab鍵,或按鼠標點擊的元素。 - 具有焦點的元素通常是通過瀏覽器突出顯示的,比如,點線圍繞的元素線。焦點是用于確定哪些元素是第一個接收鍵盤相關的事件。
舉例來說,請看下面的HTML:
<form> <input id="target" type="text" value="Field 1" /> <input type="text" value="Field 2" /> </form> <div id="other"> Trigger the handler </div>
這個事件處理函數可以綁定到第一個 input field
$('#target').focus(function() { alert('Handler for .focus() called.'); });
現(xiàn)在,如果點擊第一個表單域或按tab鍵從其他地方切換到這個表單域,警報顯示:
Handler for .focus() called.
我們可以點擊另一個元素觸發(fā)這個事件:
$('#other').click(function() { $('#target').focus(); });
這些代碼執(zhí)行后,點擊Trigger the handler也提醒消息。
focus
事件不會在Internet Explorer中泡沫。因此,用focus
事件委派,跨瀏覽器無法正常工作。
在Internet Explorer中,在隱藏的元素上觸發(fā)focus事件會導致錯誤。在可見元素上,只調用不帶參數的
.focus()
要小心。
Examples:
Example: 獲取焦點
<!DOCTYPE html>
<html>
<head>
<style>span {display:none;}</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<p><input type="text" /> <span>focus fire</span></p>
<p><input type="password" /> <span>focus fire</span></p>
<script>
$("input").focus(function () {
$(this).next("span").css('display','inline').fadeOut(1000);
});
</script>
</body>
</html>
Demo:
Example: 為了阻止人們在文本輸入框輸入,try:
$("input[type=text]").focus(function(){
$(this).blur();
});
Example: To focus on a login input box with id 'login' on page startup, try:
$(document).ready(function(){
$("#login").focus();
});