Jquery focus()
当元素获得焦点时,发生jQuery focus事件。
此事件隐式用于有限的元素集,例如<input>,<select>等表单元素以及链接<a href>。浏览器通常会以某种方式突出显示焦点所在的元素。
focus方法通常与blur()方法一起使用。
语法:
它触发选定元素的焦点事件。
$(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>
输出: