个性化阅读
专注于IT技术分析

jQuery focus()

本文概述

jQuery焦点事件在元素获得焦点时发生。它是通过单击鼠标或导航到它来生成的。

此事件隐式用于有限的元素集, 例如<input>, <select>等表单元素和链接<a href>。浏览器通常会以某种方式突出显示焦点所在的元素。

focus方法通常与blur()方法一起使用。

句法:

$(selector).focus()

它触发选定元素的焦点事件。

$(selector).focus(function)

它为焦点事件添加了一个功能。

jQuery focus()事件的参数

参数 描述
Function 它是一个可选参数。它用于指定元素获得焦点时要运行的函数。

jQuery focus()事件的示例

让我们以一个示例来演示jQuery focus()事件。

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>focus demo</title>
  <style>
  span {
    display: none;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
 <p><input type="text"> <span>Focus starts.. Write your name.</span></p>
<p><input type="password"> <span>Focus starts.. Write your password.</span></p>
 <script>
$( "input" ).focus(function() {
  $( this ).next( "span" ).css( "display", "inline" ).fadeOut( 2000 );
});
</script>
 </body>
</html>

立即测试

输出:

开始关注。写上你的名字。

焦点开始。。输入密码。

如果要阻止人们在上面的示例中在文本输入框中书写, 请尝试以下代码。

它将禁止在文本框中写入。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>focus demo</title>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
 <p><input type="text" value="you can't write"></p>
<p><input type="password"> </p>
 <script>
$( "input[type=text]" ).focus(function() {
  $( this ).blur();
});
</script>
 </body>
</html>

立即测试

赞(0)
未经允许不得转载:srcmini » jQuery focus()

评论 抢沙发

评论前必须登录!