jQuery focus()是一種內置方法,用於關注元素。該元素通過鼠標單擊或tab-navigating 按鈕獲得焦點。
用法:
$(selector).focus(function)
這裏的selector就是被選擇的元素。
參數:它接受回調函數形式的可選參數,一旦焦點事件發生就會調用該回調函數。
示例 1:下麵的示例解釋了 focus() 方法以及傳遞給它的回調函數。
HTML
<!DOCTYPE html>
<html>
<head>
<style>
span {
display: none;
}
body {
width: 35%;
height: 50px;
border: 2px solid green;
padding: 35px;
margin: 10px;
}
</style>
<script src=
"https://code.jquery.com/jquery-1.10.2.js">
</script>
</head>
<body>
<!-- this paragraph element get focused -->
<p>
<input type="text"> <span>focused</span>
</p>
<!-- jQuery code to show working of this method -->
<script>
$("input").focus(function () {
$(this).next("span").css(
"display", "inline");
});
</script>
</body>
</html>
輸出:
示例 2:在下麵的示例中,調用 focus() 方法時不帶任何參數。
HTML
<!DOCTYPE html>
<html>
<head>
<style>
span {
display: none;
}
body {
width: 30%;
height: 50px;
border: 2px solid green;
padding: 35px;
margin: 10px;
}
</style>
<script src=
"https://code.jquery.com/jquery-1.10.2.js">
</script>
</head>
<body>
<!-- this paragraph element get focused -->
<p>
<input type="text"> <span>focused</span>
</p>
<!-- jQuery code to show working of this method -->
<script>
$("input").focus();
</script>
</body>
</html>
輸出:
相關用法
- JQuery focus()用法及代碼示例
- JQuery focusin()用法及代碼示例
- JQuery focusout()用法及代碼示例
- JQuery fadeOut()用法及代碼示例
- JQuery fadeIn()用法及代碼示例
- JQuery fadeTo()用法及代碼示例
- JQuery filter()用法及代碼示例
- JQuery find()用法及代碼示例
- JQuery first()用法及代碼示例
- JQuery fadeToggle()用法及代碼示例
- JQuery finish()用法及代碼示例
- JQuery andSelf()用法及代碼示例
- JQuery change()用法及代碼示例
- JQuery each()用法及代碼示例
- JQuery end()用法及代碼示例
- JQuery height()用法及代碼示例
- JQuery innerHeight()用法及代碼示例
- JQuery keydown()用法及代碼示例
- JQuery keypress()用法及代碼示例
- JQuery next()用法及代碼示例
- JQuery nextAll()用法及代碼示例
- JQuery parent()用法及代碼示例
- JQuery parents()用法及代碼示例
- JQuery prev()用法及代碼示例
- JQuery prevAll()用法及代碼示例
注:本文由純淨天空篩選整理自kundankumarjha大神的英文原創作品 jQuery focus() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。