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


JQuery focus()用法及代碼示例

focus()是jQuery中的內置方法,用於專注於元素。通過單擊鼠標或通過tab-navigating按鈕可以使元素聚焦。
用法:

$(selector).focus(function)

選擇器是選定的元素。
參數:它接受可選參數“function”,該參數指定發生焦點事件時要運行的函數。
返回值:它返回被選中的元素。

jQuery代碼顯示focus()方法的用法方式:

代碼1:
在下麵的代碼中,一個函數被傳遞給此方法。


<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 cdee to show working of this method -->
    <script> 
        $("input").focus(function() { 
            $(this).next("span").css("display", "inline"); 
        }); 
    </script> 
  
</body> 
  
</html>

輸出:
在鼠標單擊輸入字段內部之前,

鼠標在帶有文本“GeeksforGeeks”-的輸入字段中單擊後

代碼2:
在下麵的代碼中,沒有參數傳遞給該方法。

<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>

輸出:
在輸入字段內單擊鼠標之前,

在帶有文本“GeeksforGeeks”-的輸入字段中單擊鼠標後



相關用法


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