學習JS發送自定義鍵盤(KeyboardEvent)事件的過程中,遇到了一個小難題:單個按鍵Tab可以正常發送,焦點能夠轉移到下一個元素,但想實現Shift+Tab,反向移動焦點時,卻被DOM3的瀏覽器兼容性問題難到了。
- 根據參考資料1(淺談Javascript事件模擬 - Mr_BackKom - 博客園 )的方法,行不通,因為我的瀏覽器是在Webkit核心下。
- 再找參考資料2(Document Object Model Events #Events-KeyboardEvent),了解了DOM3中的 KeyboardEvent.initKeyboardEvent 函數的定義如下:
void initKeyboardEvent(in DOMString typeArg, in boolean canBubbleArg, in boolean cancelableArg, in views::AbstractView viewArg, in DOMString keyIdentifierArg, in unsigned long keyLocationArg, in DOMString modifiersList);
根據資料1的經驗,使用DOM3標准來調用,結果還是失敗。
- 無奈之下,只好下載Webkit源代碼直接尋找該核心實現的源代碼函數原型,結果如下:
void KeyboardEvent::initKeyboardEvent(const AtomicString& type, bool canBubble, bool cancelable, AbstractView* view, const String &keyIdentifier, unsigned location, bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, bool altGraphKey) { if (dispatched()) return; initUIEvent(type, canBubble, cancelable, view, 0); m_keyIdentifier = keyIdentifier; m_location = location; m_ctrlKey = ctrlKey; m_shiftKey = shiftKey; m_altKey = altKey; m_metaKey = metaKey; m_altGraphKey = altGraphKey; }
按此原型再次調用,終於成功!(PS:開源就是好啊!)
模擬Shift+Tab代碼如下:
var evt = document.createEvent("KeyboardEvent"); evt.initKeyboardEvent("keydown", true, false, window, 'U+0009',0,false,false,true,false,false); e.currentTarget.dispatchEvent(evt);
By:Asion Tang
AT:2013年9月20日 23:58:40