Key Press

simulate Key Press

此腳本不應該直接安裝,它是一個供其他腳本使用的函式庫。欲使用本函式庫,請在腳本 metadata 寫上: // @require https://update.gf.qytechs.cn/scripts/451574/1095111/Key%20Press.js

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

!(function (moduleName, definition) {
  // Whether to expose Keyvent as an AMD module or to the global object.
  if (typeof define === 'function' && typeof define.amd === 'object') define(definition);
  else this[moduleName] = definition();

})('keyvent', function definition () {

  function contextOn (element) {
    var exports = {};
    exports.on = contextOn;

    exports.down = function (keys) {
      dispatch(element, 'keydown', keys);
    };

    exports.up = function (keys) {
      dispatch(element, 'keyup', keys);
    };

    return exports;
  }

  function dispatch (element, type, keys) {
    var event = document.createEvent('HTMLEvents');
    event.initEvent(type, true, true);
    keys = normalizeKeys(keys);
    for (var i = 0; i < keys.length; i++) {
      var keyCode = toKeyCode(keys[i]);
      event.which = event.keyCode = keyCode;
      if (MODIFIERS[keyCode]) event[MODIFIERS[keyCode] + 'Key'] = true;
      element.dispatchEvent(event);
    }
  }

  function normalizeKeys (keys) {
    if (!keys) return [0];
    if (isString(keys)) return keys.split(' ');
    return [keys];
  }

  function isString (object) { return typeof object === 'string'; }

  // Borrowed from https://github.com/madrobby/keymaster
  var ALIASES = {
    '⇧': 16, 'shift': 16,
    '⌃': 17, 'ctrl': 17, 'control': 17,
    '⌥': 18, 'alt': 18, 'option': 18,
    '⌘': 91, 'command': 91,
    'backspace': 8, 'tab': 9,
    'clear': 12, 'enter': 13,
    'return': 13, 'esc': 27,
    'escape': 27, 'space': 32,
    'left': 37, 'up': 38,
    'right': 39, 'down': 40,
    'del': 46, 'delete': 46,
    'home': 36, 'end': 35,
    'pageup': 33, 'pagedown': 34,
    ',': 188, '.': 190,
    '/': 191, '`': 192,
    '-': 189, '=': 187,
    ';': 186, '\'': 222,
    '[': 219, ']': 221,
    '\\': 220
  };
  for (key = 1; key < 20; key++) ALIASES['f' + key] = ALIASES['F' + key] = 111 + key;

  var MODIFIERS = {
    '16': 'shift',
    '17': 'ctrl',
    '18': 'alt',
    '91': 'meta'
  };

  function toKeyCode(key) {
    if (isString(key)) return ALIASES[key] || key.toUpperCase().charCodeAt(0);
    return key;
  }

  return contextOn(document);
});