Как вызвать нажатие клавиши с чистым javascript? - PullRequest
0 голосов
/ 14 июля 2020

Я пытаюсь получить нажатие клавиши, в данном случае NumPad0, или Alt, или PageUp, или PageDown, или комбинацию, например Ctrl + A, при нажатии кнопки HTML, в зависимости от ее идентификатора.

Например,

<button id="myButton">Button</button>

Когда нажимается кнопка,

function simulateClick(id) {
    var clickEvent = document.createEvent("MouseEvents");
    clickEvent.initMouseEvent("click", true, true, window, 1, 0, 0, 0, 0,
        false, false, false, false, 0, null);

    var element = document.getElementById('myButton');
    element.dispatchEvent(new KeyboardEvent('keypress',{'key':'PageDown'}));
}

Однако, когда я нажимаю, ничего не происходит.

В конечном итоге цель для запуска сценария autohotkey, который привязан к определенным клавишам и комбинациям клавиш, чтобы эффективно нажатие кнопки просто запускало эту часть сценария autohotkey, как если бы я нажал кнопку клавиатуры.

Я видел, как это сделать это с jquery, но мне нужно использовать чистый js. Как я могу вызвать нажатие клавиши с чистым javascript?

1 Ответ

0 голосов
/ 14 июля 2020

Если вы хотите смоделировать нажатие клавиши, вы на правильном пути.

Сначала добавьте событие, которое вы хотите смоделировать, в документ / элемент, затем вы можете добавить прослушиватель щелчка к кнопке, чтобы активируйте это событие, которое вы слушаете.

Запуск ключевого события не будет фактически прокручивать документ за вас, вам понадобится способ программной прокрутки страницы. В этой статье, озаглавленной «Прокрутка страниц в ванили JavaScript» , есть функция, имитирующая прокрутку. Я адаптировал его ниже. Я заставил его прокручивать 25% высоты документа за раз. Однако кнопка Page Down зависит от того, какая часть документа прокручивается.

Обратите внимание, что автор обновил свое сообщение, указав, что существует полифилл для window.scroll доступно, может работать лучше.

const AUTO_SCROLL = false

const btn = document.querySelector('#my-button')
const ara = document.querySelector('#my-textarea')

document.addEventListener('keydown', onKeyPress)
btn.addEventListener('click', simulateClick)

function onKeyPress(e) {
  if (e.key === 'PageDown') {
    ara.value += 'DOWN\n'
  }
}

function simulateClick(e) {
  // Scroll the document
  if (AUTO_SCROLL) {
    const documentHeight = Math.max(document.body.scrollHeight,
      document.body.offsetHeight, document.documentElement.clientHeight,
      document.documentElement.scrollHeight, document.documentElement.offsetHeight);
    scrollIt(window.pageYOffset + (documentHeight * 0.25))
  }
  // Fire the event to handle the rest...
  document.dispatchEvent(new KeyboardEvent('keydown', {
    key: 'PageDown'
  }))
}

/** Source: https://pawelgrzybek.com/page-scroll-in-vanilla-javascript/ */
function scrollIt(destination, duration = 200, easing = 'linear', callback) {
  const easings = {
    linear(t) {
      return t;
    },
    easeInQuad(t) {
      return t * t;
    },
    easeOutQuad(t) {
      return t * (2 - t);
    },
    easeInOutQuad(t) {
      return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
    },
    easeInCubic(t) {
      return t * t * t;
    },
    easeOutCubic(t) {
      return (--t) * t * t + 1;
    },
    easeInOutCubic(t) {
      return t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1;
    },
    easeInQuart(t) {
      return t * t * t * t;
    },
    easeOutQuart(t) {
      return 1 - (--t) * t * t * t;
    },
    easeInOutQuart(t) {
      return t < 0.5 ? 8 * t * t * t * t : 1 - 8 * (--t) * t * t * t;
    },
    easeInQuint(t) {
      return t * t * t * t * t;
    },
    easeOutQuint(t) {
      return 1 + (--t) * t * t * t * t;
    },
    easeInOutQuint(t) {
      return t < 0.5 ? 16 * t * t * t * t * t : 1 + 16 * (--t) * t * t * t * t;
    }
  };

  const start = window.pageYOffset;
  const startTime = 'now' in window.performance
    ? performance.now() : new Date().getTime();

  const documentHeight = Math.max(document.body.scrollHeight,
    document.body.offsetHeight, document.documentElement.clientHeight,
    document.documentElement.scrollHeight, document.documentElement.offsetHeight);
  const windowHeight = window.innerHeight ||
    document.documentElement.clientHeight ||
    document.getElementsByTagName('body')[0].clientHeight;
  const destOffset = typeof destination === 'number'
    ? destination : destination.offsetTop;
  const destOffScroll = Math.round(documentHeight - destOffset < windowHeight
    ? documentHeight - windowHeight : destOffset);

  if ('requestAnimationFrame' in window === false) {
    window.scroll(0, destOffScroll);
    if (callback) {
      callback();
    }
    return;
  }

  function scroll() {
    const now = 'now' in window.performance ? performance.now() : new Date().getTime();
    const time = Math.min(1, ((now - startTime) / duration));
    const timeFunction = easings[easing](time);
    window.scroll(0, Math.ceil((timeFunction * (destOffScroll - start)) + start));

    if (window.pageYOffset === destOffScroll) {
      if (callback) {
        callback();
      }
      return;
    }
    
    requestAnimationFrame(scroll);
  }

  scroll();
}
#my-button {
  position: fixed;
  right: 4em;
  top: 1.33em;
}
<textarea id="my-textarea" rows="100" cols="62"></textarea>
<button id="my-button">Button</button>
...