The keydown event is sent to an element when the user first presses a key on the keyboard. It can be attached to any element, but the event is only sent to the element that has the focus. Focusable elements can vary between browsers, but form elements can always get focus so are reasonable candidates for this event type.
以上是從jquery文檔中copy下的一段文本,它說明我們可以給form元素綁定keydown事件,因為它們可以獲取焦點,但怎樣去給p、span綁定呢?
答案就是tabindex這個屬性
js中改變這個屬性:jsObj.tabIndex
jquery : $(selector).attr("tabindex",value)
元素的tabindex屬性用來定義元素是否可以獲取焦點,是否可以通過連續的焦點導航(一般情況是按tab鍵)獲取焦點,與你獲取焦點的順序。
其值必須是整數值。
如果沒有設置,或者設置的值不正確,則按照慣例執行。
如果是負數,用戶不可以通過連續的焦點導航獲取焦點,但可以用其他方式獲取焦點。
如果是零,則可以通過連續的焦點導航獲取焦點,按照慣例確定順序。
如果是正數,則可以通過連續的焦點導航獲取焦點,按照該值確定順序。
p默認是得不到焦點的,可以為其設置tabindex屬性使其可以獲得焦點。也就可以綁定鍵盤事件。
事例 :
<span id="myspan"></span> js: $("#myspan").attr("tabindex",0); $("#myspan").focus(); $("#myspan").keydown(function() { alert('Handler for .keydown() called.'); });
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com