前天改一個bug, js 實現的一個 面板拖拉,左右各兩個列表,中間面板畫線連接,頁面左側列表選中后,key 事件無效。右側選中確有效,很奇怪,查看源碼,左側選中后,$(document).on("keydown",function(event){} 對左側無效,由於無異常拋出,只能一點點代碼。一個字,累。
確定頁面部分div失去焦點,索性,給外面最大div 添加一個 獲取焦點事件,解決 。
$("#myspan").attr("tabindex",0);
$("#myspan").focus();
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事件,因為它們可以獲取焦點,但怎樣去給div、span綁定呢?
答案就是tabindex這個屬性
js中改變這個屬性:jsObj.tabIndex
jquery : $(selector).attr("tabindex",value)
tabindex
元素的tabindex屬性用來定義元素是否可以獲取焦點,是否可以通過連續的焦點導航(一般情況是按tab鍵)獲取焦點,與你獲取焦點的順序。
其值必須是整數值。
如果沒有設置,或者設置的值不正確,則按照慣例執行。
如果是負數,用戶不可以通過連續的焦點導航獲取焦點,但可以用其他方式獲取焦點。
如果是零,則可以通過連續的焦點導航獲取焦點,按照慣例確定順序。
如果是正數,則可以通過連續的焦點導航獲取焦點,按照該值確定順序。
div默認是得不到焦點的,可以為其設置tabindex屬性使其可以獲得焦點。也就可以綁定鍵盤事件。
事例 :
<span id="myspan"></span>
js:
$("#myspan").attr("tabindex",0);
$("#myspan").focus();
此文章來自網絡轉載
