首页 > 解决方案 > 如何模拟按下 END 键

问题描述

我有一个从 aspx.vb 文件中调用的 javascript 函数:

using ScriptManager.RegisterStartupScript(Me, Page.GetType, "Script", "pressKey();", True)

我需要该pressKey功能来模拟END按键,就像用户在键盘上按下它一样。

标签: javascript

解决方案


End 键的 charCode 是 35。CSS 技巧有一个很好的字符代码列表:https ://css-tricks.com/snippets/javascript/javascript-keycodes/

这是 Vanilla JS 解决方案:

var keyboardEvent = document.createEvent("KeyboardEvent");
var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? 
"initKeyboardEvent" : "initKeyEvent";


keyboardEvent[initMethod](
               "keydown", // event type : keydown, keyup, keypress
                true, // bubbles
                true, // cancelable
                window, // viewArg: should be window
                false, // ctrlKeyArg
                false, // altKeyArg
                false, // shiftKeyArg
                false, // metaKeyArg
                35, // keyCodeArg : unsigned long the virtual key code, else 0
                0 // charCodeArgs : unsigned long the Unicode character associated with the depressed key, else 0
);
document.dispatchEvent(keyboardEvent);

推荐阅读