學習JS發送自定義鍵盤(KeyboardEvent)事件的過程當中,遇到了一個小難題:單個按鍵Tab能夠正常發送,焦點可以轉移到下一個元素,但想實現Shift+Tab,反向移動焦點時,卻被DOM3的瀏覽器兼容性問題難到了。html
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標準來調用,結果仍是失敗。瀏覽器
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:40spa