.focus()

.focus( handler(eventObject) ) 官网原E文: jQuery

描述: 为 "focus" 事件绑定一个处理函数,或者触发元素上的 "focus" 事件。

  • version added: 1.0.focus( handler(eventObject) )

    handler(eventObject)每次事件触发时会执行的函数。

  • version added: 1.4.3.focus( [ eventData ], handler(eventObject) )

    eventData将要传递给事件处理函数的数据映射。

    handler(eventObject)每次事件触发时会执行的函数。

  • version added: 1.0.focus()

  • 这个函数的第一种用法是 .bind('focus', handler) 的快捷方式,第二种用法是 .trigger('focus') 的快捷方式。
  • focus事件被发送到一个获得焦点时的元素。此事件隐式适用于有限的元素,比如表单元素(<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.');
});

现在,如果点击第一个表单域或按tab键从其他地方切换到这个表单域,警报显示:

Handler for .focus() called.

我们可以点击另一个元素触发这个事件:

$('#other').click(function() {
  $('#target').focus();
});

这些代码执行后,点击Trigger the handler也提醒消息。

focus事件不会在Internet Explorer中泡沫。因此,用focus事件委派,跨浏览器无法正常工作。

在Internet Explorer中,在隐藏的元素上触发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();
});
jQuery 1.6 API 中文版Clove整理、修订