
- jQuery 教程
- jQuery - 首頁
- jQuery - 路線圖
- jQuery - 概述
- jQuery - 基礎
- jQuery - 語法
- jQuery - 選擇器
- jQuery - 事件
- jQuery - 屬性
- jQuery - AJAX
- jQuery DOM 操作
- jQuery - DOM
- jQuery - 新增元素
- jQuery - 刪除元素
- jQuery - 替換元素
- jQuery CSS 操作
- jQuery - CSS 類
- jQuery - 尺寸
- jQuery - CSS 屬性
- jQuery 效果
- jQuery - 效果
- jQuery - 動畫
- jQuery - 鏈式操作
- jQuery - 回撥函式
- jQuery 遍歷
- jQuery - 遍歷
- jQuery - 遍歷祖先節點
- jQuery - 遍歷子孫節點
- jQuery UI
- jQuery - 互動
- jQuery - 小部件
- jQuery - 主題
- jQuery 參考
- jQuery - 選擇器
- jQuery - 事件
- jQuery - 效果
- jQuery - HTML/CSS
- jQuery - 遍歷
- jQuery - 其他
- jQuery - 屬性
- jQuery - 工具函式
- jQuery 外掛
- jQuery - 外掛
- jQuery - PagePiling.js
- jQuery - Flickerplate.js
- jQuery - Multiscroll.js
- jQuery - Slidebar.js
- jQuery - Rowgrid.js
- jQuery - Alertify.js
- jQuery - Progressbar.js
- jQuery - Slideshow.js
- jQuery - Drawsvg.js
- jQuery - Tagsort.js
- jQuery - LogosDistort.js
- jQuery - Filer.js
- jQuery - Whatsnearby.js
- jQuery - Checkout.js
- jQuery - Blockrain.js
- jQuery - Producttour.js
- jQuery - Megadropdown.js
- jQuery - Weather.js
- jQuery 有用資源
- jQuery - 問答
- jQuery - 快速指南
- jQuery - 有用資源
- jQuery - 討論
jQuery 事件 focus() 方法
jQuery 的 focus() 事件方法用於將事件處理程式附加到 focus 事件或在選定的元素上觸發該事件。當元素獲得焦點時,無論是透過滑鼠點選還是透過選項卡導航,都會發生 focus 事件。
語法
以下是 jQuery 事件 focus() 方法的語法:
$(selector).focus(function)
引數
此方法接受一個可選的引數作為函式,如下所述:
- function - 當 focus 事件發生時要執行的可選函式。
返回值
此方法沒有返回值。
示例 1
以下程式演示了 jQuery 事件 focus() 方法的使用:
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script> </head> <body> <p>Click on the below button to highlight this text.</p> <button>Focus on above text</button> <script> $('button').focus(function(){ $('p').css("color", "red"); }); </script> </body> </html>
輸出
以上程式顯示一條訊息和一個按鈕。當點選按鈕時,文字顏色更改為“紅色”:
當用戶點選顯示的按鈕時:
示例 2
當 input 欄位獲得焦點時突出顯示它。
以下是 jQuery 事件 focus() 方法的另一個示例。我們使用此方法將焦點設定到輸入欄位:
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script> </head> <body> <p>Click on the below input field to get focused.</p> <label for="">Enter your name: </label> <input type="text" placeholder="Name"> <script> $('input').focus(function(){ $(this).css({"background-color":"green", "color":"white"}); }); </script> </body> </html>
輸出
執行程式後,將顯示一個輸入欄位。當用戶點選此輸入欄位時,它將獲得焦點:
當用戶點選輸入欄位時:
示例 3
在不使用 function 引數的情況下使用 focus() 方法。
在下面的示例中,我們使用了 jQuery 的 focus() 事件方法,而沒有指定函式。當程式執行時,輸入欄位將自動獲得焦點:
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script> <style> input{ width: 200px; padding: 10px 10px; } </style> </head> <body> <label for="">Enter your name: </label> <input type="text" placeholder="Name"> <script> $('input').focus(); </script> </body> </html>
輸出
執行上述程式後,它顯示一個獲得焦點的輸入欄位:
jquery_ref_events.htm
廣告