如何使用虚拟键盘在光标所在的位置写字符?

问题描述 投票:0回答:1

我正在使用实时HTML编辑器。它基本上是针对移动用户的。因此,我制作了一个带有HTML标签的虚拟键盘。但是,我遇到了一个问题:键盘只在另一个标签的末尾打印标签。因此它无法按我希望的那样工作。

这里是代码。

(function() {
  'use strict';
  var i, c, t, delay = 5000,
    kb = document.getElementById('keyboard');
  /* get all the input elements within the div whose id is "keyboard */
  i = kb.getElementsByTagName('input');
  /* loop through all the elements */

  for (c = 0; c < i.length; c++) {
    /* find all the the input type="button" elements */
    if (i[c].type === 'button') {
      /* add an onclick handler to each of them  and set the function to call */
      i[c].addEventListener('onclick', makeClickHandler(c));
    }
  }

  /* this is the type="reset" input */
  document.getElementById('clear').addEventListener('click',
    function() {
      /* remove all the characters from the input type="text" element */
      document.getElementById('text').value = '';
    }, false);

  function makeClickHandler(c) {
    i[c].onclick = function() {
      /* find the non-text button  which has an id */
      if (i[c].id === 'back') {
        /* remove last character from the input the type="text" element using regular expression */
        document.getElementById('text').value =
          document.getElementById('text').value.replace(/.$/, '');
      }
      /* find the text buttons */
      else {
        /* add characters to the input type="text" element */
        document.getElementById('text').value += this.value.toLowerCase();
      }
    };
  }
  document.onmousemove = resetTimer;
  document.onkeypress = resetTimer;

  function logout() {
    kb.classList.remove('show');
    kb.classList.add('hide');
  }

  function resetTimer() {
    clearTimeout(t);
    t = setTimeout(logout, delay)
  }
  resetTimer();
})();
<div id="keyboard" class="show">

  <div>
    <input type="button" value="Q">
    <input type="button" value="W"> .........
    <input type="button" value="V">
    <input type="button" value="B">
    <input type="button" value="N">
    <input type="button" value="M">
  </div>
  <div>
    <input id="back" type="button" value="&#8592;">
    <input id="space" type="button" value=" ">
    <input id="clear" type="reset" value="clear">
  </div>
  <div>
    <label>Track Search</label> - <input id="text" type="text">
  </div>

  <!-- #keyboard -->
</div>

使用此代码,我只能在最后一个打印的字符之后打印。但是我想要这样(|表示光标位置),

An|ant

我在An之前写了ant

但是它像这样打印它:

ant An|

我该怎么做才能解决问题?

javascript html cursor-position virtual-keyboard
1个回答
0
投票

我想您搜索的是selectionStartYou can use it in major browsers因此您可以在[

中获得添加位置的起点(而不是简单地附加到字符串的末尾)
.value += this.value.toLowerCase();

您可以像这样简单地使用它:

var input = document.getElementById('text');
var caretPosition = input.selectionStart;

// Check if there is a Selection in your input
if (input.selectionStart != input.selectionEnd)
{
   var selectionValue =
   input.value.substring(input.selectionStart, input.selectionEnd);
}
© www.soinside.com 2019 - 2024. All rights reserved.