當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


JQuery focus()用法及代碼示例

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>

輸出:



相關用法


注:本文由純淨天空篩選整理自kundankumarjha大神的英文原創作品 jQuery focus() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。