Виртуальная клавиатура

Материал из Department of Theoretical and Applied Mechanics
Версия от 15:08, 18 мая 2015; Денис (обсуждение | вклад)

(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск
Виртуальная лаборатория > Виртуальная клавиатура

Простейшая реализация виртуальной клавиатуры, со звуками нажатия клавиш и буфером всех введенных символов. В полноэкранном режиме буфер символов и интерфейс копирования скрываются. (Чтобы перейти в полноэкранный режим, нажмите F11).

Ширина клавиатуры подстраивается под размер экрана/браузера.

"Виртуальная клавиатура" (скрипт выложен отдельной страницей, т.к. предполагается использование в полноэкранном режиме).


Звук нажатия клавиши взят из репозитория Freesound.org

Скачать программу: Virtual_Keyboard.zip

Текст программы на языке JavaScript (разработчик Цветков Денис):

Файл "Virtual_Keyboard.html"

  1 <!DOCTYPE html>
  2 <html>
  3 <head>
  4     <meta charset="UTF-8" />
  5     <title>Виртуальная клавиатура</title>
  6 </head>
  7 <body>
  8     <!--<условие onkeypress предотвращает нажатие любых кнопок, кроме F5 и F11>-->
  9     <input id="text" style="width: 100%; font-family:monospace; font-weight:bold; " onkeypress="if (event.keyCode != 122 && event.keyCode != 116) return false;">
 10     <div id="container"></div>
 11     <br><br>
 12     <div id="copy_GUI">
 13         <!--<Современные браузеры блокируют изменение буфера обмена напрямую из javascript кода>-->
 14         <input id="all_text" style="width: 100%; font-family:monospace; " onkeypress="if (event.keyCode != 122 && event.keyCode != 116) return false;">
 15         <input type="button" id="select_all" onclick="all_text.focus(); all_text.setSelectionRange(0, all_text.value.length);" value="Выделить всё"/>
 16         Выделите и нажмите Ctrl + C, чтобы скопировать в буфер обмена
 17     </div>
 18 
 19     <script>
 20         document.oncontextmenu = function() {return false;};      // блокировка контекстного меню
 21 
 22         var button_width, char_size;            // ширина кнопки, размер шрифта
 23         var buttons_buffer = "";                // буфер кнопок, который запоминает все введенные кнопки
 24         var extra_string = "";                  // сюда заносятся символы, не помещающиеся на экран
 25 
 26         function count_sizes() {                 // считаем нужные размеры букв и кнопок
 27             button_width = document.documentElement.clientWidth / 10 - 4;
 28             char_size = button_width - 10;
 29         }
 30         count_sizes();
 31 
 32         // создадим кнопки
 33         var chars = "АБВГДЕЁ←\nЖЗИЙКЛМНО\nПРСТУФХЦЧ\nШЩЪЫЬЭЮЯ ";
 34         for (var ch = 0; ch < chars.length; ch++) {
 35             if (chars[ch] == '\n') container.innerHTML += "<br>";
 36             else if (chars[ch] == '←') container.innerHTML += "<input type='button' id='b" + ch + "' onmousedown='press_button(\"" + chars[ch] + "\"); return false;' value='←'/>";
 37             else if (chars[ch] == ' ') container.innerHTML += "<input type='button' id='b" + ch + "' onmousedown='press_button(\"" + chars[ch] + "\"); return false;' value='˽'/>";
 38             else container.innerHTML += "<input type='button' id='b" + ch + "' onmousedown='press_button(\"" + chars[ch] + "\"); return false;' value='"+ chars[ch] + "'/>";
 39         }
 40 
 41         function press_button(c) {
 42             if (c == '←') {
 43                 if (text.value.length != 0) {   // не объединять с пред. условием, т.к. далее идет else
 44                     if (extra_string.length > 0) {
 45                         text.value = extra_string[extra_string.length - 1] + text.value.substring(0, text.value.length - 1);
 46                         extra_string = extra_string.substring(0, extra_string.length - 1);
 47                     } else {
 48                         text.value = text.value.substring(0, text.value.length - 1);
 49                     }
 50                     buttons_buffer += c;
 51                 }
 52             } else {
 53                 if (text.value.length < 16) {
 54                     text.value += c;
 55                 } else {
 56                     extra_string = extra_string + text.value[0];
 57                     text.value = text.value.substring(1, text.value.length) + c;
 58                 }
 59                 buttons_buffer += c;
 60             }
 61 
 62             sound_click();
 63             text.focus();
 64             all_text.value = buttons_buffer;
 65         }
 66 
 67         function sound_click() {                // звук при нажатии клавиши
 68             var audio = new Audio();            // Создаём новый элемент Audio
 69             audio.src = 'button_sound.wav';     // Указываем путь к звуку "клика"
 70             audio.autoplay = true;              // Автоматически запускаем
 71         }
 72 
 73         function resize() {                     // размеры кнопок в зависимости от размеров экрана
 74             count_sizes();
 75             text.style.fontSize = button_width + "px";
 76             for (var ch = 0; ch < chars.length; ch++) {
 77                 var e = document.getElementById('b' + ch);
 78                 if (e != null) {
 79                     e.style.fontSize = char_size + "px";
 80                     if (chars[ch] == "←") e.style.width = button_width * 3 + "px";
 81                     else if (chars[ch] == " ") e.style.width = button_width * 2 + "px";
 82                     else e.style.width = button_width + "px";
 83                 }
 84             }
 85         }
 86 
 87         function check_copy_GUI_visibility() {  // если полноэкранный режим - убрать интерфейс копирования
 88             if( (screen.availHeight || screen.height - 5) <= window.innerHeight) {
 89                 copy_GUI.style.display = "none";
 90                 copy_GUI.style.visibility = "hidden";
 91             } else {
 92                 copy_GUI.style.display = "inline";
 93                 copy_GUI.style.visibility = "visible";
 94             }
 95         }
 96 
 97         resize();
 98         check_copy_GUI_visibility();
 99         window.onresize = function() {resize(); check_copy_GUI_visibility();};
100     </script>
101 </body>
102 </html>