Javascript код нажатой клавишу

Element: keydown event

The keydown event is fired when a key is pressed.

Unlike the deprecated keypress event, the keydown event is fired for all keys, regardless of whether they produce a character value.

The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered. For example, a lowercase «a» will be reported as 65 by keydown and keyup , but as 97 by keypress . An uppercase «A» is reported as 65 by all events.

Keyboard events are only generated by , , and anything with the contentEditable or tabindex attribute. If not caught, they bubble up the DOM tree until they reach Document .

Since Firefox 65, the keydown and keyup events are now fired during IME composition, to improve cross-browser compatibility for CJKT users (Firefox bug 354358). To ignore all keydown events that are part of composition, do something like this (229 is a special value set for a keyCode relating to an event that has been processed by an IME):

.addEventListener("keydown", (event) =>  if (event.isComposing || event.keyCode === 229)  return; > // do something >); 

Syntax

Use the event name in methods like addEventListener() , or set an event handler property.

addEventListener("keydown", (event) => >); onkeydown = (event) => >; 

Event type

Event properties

This interface also inherits properties of its parents, UIEvent and Event . KeyboardEvent.altKey Read only Returns a boolean value that is true if the Alt ( Option or ⌥ on macOS) key was active when the key event was generated. KeyboardEvent.code Read only Returns a string with the code value of the physical key represented by the event.

Warning: This ignores the user’s keyboard layout, so that if the user presses the key at the «Y» position in a QWERTY keyboard layout (near the middle of the row above the home row), this will always return «KeyY», even if the user has a QWERTZ keyboard (which would mean the user expects a «Z» and all the other properties would indicate a «Z») or a Dvorak keyboard layout (where the user would expect an «F»). If you want to display the correct keystrokes to the user, you can use Keyboard.getLayoutMap() .

KeyboardEvent.ctrlKey Read only Returns a boolean value that is true if the Ctrl key was active when the key event was generated. KeyboardEvent.isComposing Read only Returns a boolean value that is true if the event is fired between after compositionstart and before compositionend . KeyboardEvent.key Read only Returns a string representing the key value of the key represented by the event. KeyboardEvent.locale Read only Returns a string representing a locale string indicating the locale the keyboard is configured for. This may be the empty string if the browser or device doesn’t know the keyboard’s locale.

Note: This does not describe the locale of the data being entered. A user may be using one keyboard layout while typing text in a different language.

KeyboardEvent.location Read only Returns a number representing the location of the key on the keyboard or other input device. A list of the constants identifying the locations is shown in Keyboard locations. KeyboardEvent.metaKey Read only Returns a boolean value that is true if the Meta key (on Mac keyboards, the ⌘ Command key; on Windows keyboards, the Windows key ( ⊞ )) was active when the key event was generated. KeyboardEvent.repeat Read only Returns a boolean value that is true if the key is being held down such that it is automatically repeating. KeyboardEvent.shiftKey Read only Returns a boolean value that is true if the Shift key was active when the key event was generated.

Examples

addEventListener keydown example

input placeholder="Click here, then press down a key." size="40" /> p id="log">p> 
const input = document.querySelector("input"); const log = document.getElementById("log"); input.addEventListener("keydown", logKey); function logKey(e)  log.textContent += ` $e.code>`; > 

onkeydown equivalent

Источник

События клавиатуры в JavaScript

При вводе с клавиатуры в javascript возникает сразу несколько событий, которые позволяют отследить коды нажатых клавиш и получить дополнительную полезную информацию для полного контроля над устройством ввода. Перейдём к теоретической и практической части.

События клавиатуры

В JS для клавиатуры используется 3 основных события:

  1. onkeydown — срабатывает при нажатии на клавишу и повторяется пока её не отжали.
  2. onkeypress — идентично предыдущему, но с 2 особенностями:
    • срабатывает после «onkeydown» и только для клавиш с символами;
    • функциональные клавиши, типа Alt и Ctrl , его не задействуют.
  3. onkeyup — срабатывает один раз после отжатия.
document.addEventListener('keydown', function()< console.log('Success onkeydown'); >);
document.addEventListener('keypress', function()< console.log('Success onkeypress'); >);
document.addEventListener('keyup', function()< console.log('Success onkeyup'); >);

длительное нажатие

обычное

Для избежания повторных вызовов «keydown» и «keypress» используйте свойство «repeat». Подробнее рассмотрим его позже.

В примерах использовался метод «addEventListener», но можно встретить и другие варианты:

// устаревший способ document.onkeydown = function()< console.log('Success onkeydown'); >);
// на jQuery $(document).on('keydown', function()< console.log('Success onkeydown'); >);

Получение свойств событий

Для получения информации о клавише обратитесь к свойствам объекта «event».

document.addEventListener('keyup', function(event)< console.log('Key: ', event.key); console.log('keyCode: ', event.keyCode); >);

Свойства key и keyCode

key — возвращает значение нажатой клавиши в виде строки. Например, «F», «5» или «Enter».

keyCode — возвращает числовой код. Для события «keypress» вернёт ASCII-код нажатого символа.

Примечание. Цифры на верхнем и боковом блоке клавиатуры имеют разные «keyCode».

Коды основных функциональных клавиш:

Клавиша Key keyCode
Ввод Enter 13
Стереть Backspace 8
Удалить Delete 46
Пробел Space 32
Табулятор Tab 9
Esc Escape 27
Стрелка влево ArrowLeft 37
Стрелка вверх ArrowUp 38
Стрелка вправо ArrowRight 39
Стрелка вниз ArrowDown 40
Shift Shift 16
Ctrl Control 17
Alt Alt 18

Хорошей практикой в JavaScript считается использование «key», а не «keyCode». Это повышает читаемость кода и избавляет от необходимости запоминать соответствие кодов их значениям.

Свойства code и charCode

Актуальны только для события «keypress».

  • code — возвращает строковое наименование символа. Для букв имеет вид «keyD», «keyF». Такие значения будут возвращены независимо от установленного языка и регистра букв. Для цифр верхнего блока клавиатуры возвращает значение вида «Digit5», для бокового — «Numpad5».
  • charCode — возвращает код символа из таблицы ASCII. Код букв на разных языковых раскладках клавиатуры отличается. Регистр также имеет значение. Например, » f » имеет код 102, а » F » — 70.
document.addEventListener('keypress', function(event)< console.log('Строковый код: ', event.code); console.log('ASCII код: ', event.charCode); >);

Не поддерживаются IE и старыми версиями других браузеров.

Свойства altKey, ctrlKey, shiftKey

Позволяют отследить, зажат ли в момент события Alt , Ctrl или Shift . Удобно использовать для создания горячих клавиш.

document.addEventListener('keydown', function(event) < if (event.shiftKey && ['F','f'].includes(event.key) ) < console.log('Нажаты Shift + F или Shift + f'); >>);

Проверка зажатой клавиши Command на Mac

На устройствах компании Apple в горячих клавишах вместо Ctrl часто используют Cmd . Чтобы разграничить их действие для Mac и остальных устройств применяйте конструкцию с проверкой свойства «metaKey».

document.addEventListener('keydown', function(event)< const isCtrlCmd = window.navigator.platform.match('Mac') ? e.metaKey : e.ctrlKey; if (isCtrlCmd && event.key == '+') console.log('Ctrl/Cmd +'); if (isCtrlCmd && event.key == '-') console.log('Ctrl/Cmd -'); >);

Свойство type

Возвращает тип события в виде строки. Может использоваться, когда один обработчик применяется сразу для нескольких событий.

['keydown', 'keyup'].forEach(function(event) < window.addEventListener(event, function(event)< if (event.type == 'keydown') < console.log('Зажали. '); >else if (event.type == 'keyup') < console.log('Отжали'); >>); >);

Свойство repeat

Возвращает логическое «true», если событие уже один раз отработало и автоматически вызывается снова. Подобная ситуация возникает при зажатии клавиши на длительное время — «keydown» и «keypress» начинают срабатывать повторно.

document.addEventListener('keydown', function(event) < if (event.repeat == false) < console.log('первичное срабатывание'); >else < console.log('повторное срабатывание'); >>);

Пример проверки ввода в Input

Рассмотрим небольшой пример, в котором разрешим ввод в текстовое поле только нуля и единицы. Учитываем возможность стирания, удаления и табуляции.

// HTML // SCRIPT document.getElementById('binaryInput').addEventListener('keydown', function(event) < if (!['0','1','Backspace','Delete','Tab'].includes(event.key)) < event.preventDefault(); >>);

Метод «preventDefault()» запрещает действие по умолчанию.

Применение предыдущего обработчика ко всем текстовыми полями на странице:

document.querySelectorAll('input[type="text"]').forEach(function(element) < element.addEventListener('keydown', function(event)< if (!['0','1','Backspace','Delete','Tab'].includes(event.key)) < event.preventDefault(); >>); >);

Коды клавиш

Поставьте курсор в поле ввода и нажмите любую клавишу:

Добрый день.
Нашел два скрипта на JS которые выполняют нужные мне функции. Первый скрипт задает числа в секундах при нажатии кнопок и сумирует выдавая результат и публикует его в поле > Второй скрипт должен брать число из поля и переводит его в часы и дни выдавая результат в поле автоматически сразу как там появляется число. Но проблема в том что второй скрипт срабатывает если в поле вводить число в ручную с клавиатуры либо нажать клавишу «ENTER» если же в поле появляется число которое публикует первый скрипт при нажатии кнопки тогда второй скрипт не срабатывает. Как автоматизировать процесс чтобы при нажатии даже одной кнопки из первого скрипта появлялся конечный результат в днях и часах в поле из второго скрипта.
Например как дописать в первый скрипт функцию которая имитирует нажатие клавиши «INTER» после того как число публикуется в поле с > Идеальный вариант это убрать поле а число которое должно публиковаться в поле с чтобы передавалось сразу во второй скрипт который переводит его в дни и часы сразу выдавая результат.

              
  

Добрый день.
Вызывай в конце функции addition(), которая срабатывает каждый раз при нажатии на кнопку, функцию her(res); для пересчета значения.

Но честно говоря, весь код очень плох. Так не программируют.

Источник

Читайте также:  Get size of php array
Оцените статью