為了嘗試在Safari 瀏覽器中模擬鍵盤事件,使用JavaScript 測試了兩種方法:
方法1:
var event = document.createEvent("KeyboardEvent"); event.initKeyboardEvent("keypress", true, true, null, false, false, false, false, 115, 0);
方法2:
var event = document.createEvent("UIEvents"); event.initUIEvent("keypress", true, true, window, 1); event.keyCode = 115;
但是,執行任一程式碼後,事件物件的keyCode/which 屬性仍設定為0 ,表示不成功
解決方案:
根據DOM Keyboard Event Level 3 polyfill,可以採用以下方法:
element.addEventListener("keydown", function(e){ console.log(e.key, e.char, e.keyCode) }) var e = new KeyboardEvent("keydown", {bubbles : true, cancelable : true, key : "Q", char : "Q", shiftKey : true}); element.dispatchEvent(e); // If the legacy "keyCode" property is required: delete e.keyCode; Object.defineProperty(e, "keyCode", {"value" : 666})
其他更新:
DOM 鍵盤事件等級3 polyfill 現在支援舊屬性:
var e = new KeyboardEvent("keydown", { bubbles : true, cancelable : true, char : "Q", key : "q", shiftKey : true, keyCode : 81 });
function initKeyboardEvent(type, bubbles, cancelable, view, key, location, modifiers, repeat) { var event = document.createEvent("KeyboardEvent"); event.initKeyboardEvent(type, bubbles, cancelable, view, key, location, modifiers, repeat, false, false, false, false, false, false, 0); return event; }
以上是如何使用 JavaScript 模擬 Safari 中的鍵盤事件?的詳細內容。更多資訊請關注PHP中文網其他相關文章!