.focus()
.focus( handler(eventObject) ) 返回: jQuery
描述: 為 "focus" 事件綁定一個(gè)處理函數(shù),或者觸發(fā)元素上的 "focus" 事件。
-
version added: 1.0.focus( handler(eventObject) )
handler(eventObject)每次事件觸發(fā)時(shí)會執(zhí)行的函數(shù)。
-
version added: 1.4.3.focus( [ eventData ], handler(eventObject) )
eventData將要傳遞給事件處理函數(shù)的數(shù)據(jù)映射。
handler(eventObject)每次事件觸發(fā)時(shí)會執(zhí)行的函數(shù)。
version added: 1.0.focus()
- 這個(gè)函數(shù)的第一種用法是
.bind('focus', handler)的快捷方式,第二種用法是.trigger('focus')的快捷方式。 - 該
focus事件被發(fā)送到一個(gè)獲得焦點(diǎn)時(shí)的元素。此事件隱式適用于有限的元素,比如表單元素(<input>,<select>等)和鏈接元素(<a href>)。在最近版本的瀏覽器中,該事件可以擴(kuò)展到所有包括通過顯式設(shè)置tabindex屬性的元素類型。一個(gè)元素可以通過鍵盤命令獲得焦點(diǎn),如Tab鍵,或按鼠標(biāo)點(diǎn)擊的元素。 - 具有焦點(diǎn)的元素通常是通過瀏覽器突出顯示的,比如,點(diǎn)線圍繞的元素線。焦點(diǎn)是用于確定哪些元素是第一個(gè)接收鍵盤相關(guān)的事件。
舉例來說,請看下面的HTML:
<form> <input id="target" type="text" value="Field 1" /> <input type="text" value="Field 2" /> </form> <div id="other"> Trigger the handler </div>
這個(gè)事件處理函數(shù)可以綁定到第一個(gè) input field
$('#target').focus(function() {
alert('Handler for .focus() called.');
});
現(xiàn)在,如果點(diǎn)擊第一個(gè)表單域或按tab鍵從其他地方切換到這個(gè)表單域,警報(bào)顯示:
Handler for .focus() called.
我們可以點(diǎn)擊另一個(gè)元素觸發(fā)這個(gè)事件:
$('#other').click(function() {
$('#target').focus();
});
這些代碼執(zhí)行后,點(diǎn)擊Trigger the handler也提醒消息。
focus事件不會在Internet Explorer中泡沫。因此,用focus事件委派,跨瀏覽器無法正常工作。
在Internet Explorer中,在隱藏的元素上觸發(fā)focus事件會導(dǎo)致錯(cuò)誤。在可見元素上,只調(diào)用不帶參數(shù)的
.focus()要小心。
Examples:
Example: 獲取焦點(diǎn)
<!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();
});