как изменить фокус внутри ввода - PullRequest
0 голосов
/ 04 августа 2020

Сценарий: мне нужно изменить фокус ввода, когда пользователь нажимает клавишу ввода. тип ввода - дата. например, когда фокус находится на «дне» и пользователь нажимает клавишу ввода, фокус должен измениться на месяц (точно так же, как при нажатии табуляции).

возможно, этот фрагмент поможет решить проблему:

enter image description here

first I have tried to get the next element by querySelectorAll but the next element is the next input not next digit in the input.

function focusNextElement() {
    //add all elements we want to include in our selection
    var focussableElements =
      'a:not([disabled]), button:not([disabled]), input:not([disabled]), [tabindex]:not([disabled]):not([tabindex="-1"])';
    if (document.activeElement && document.activeElement.form) {
        var focussable = Array.prototype.filter.call(
            document.activeElement.form.querySelectorAll(focussableElements),
            function(element) {
                //check for visibility while always include the current activeElement
                return (
                    element.offsetWidth > 0 ||
                    element.offsetHeight > 0 ||
                    element === document.activeElement
                );
            }
        );
        var index = focussable.indexOf(document.activeElement);
        if (index > -1) {
            var nextElement = focussable[index + 1] || focussable[0];
            nextElement.focus();
        }
    }
}

есть идеи?

1 Ответ

0 голосов
/ 05 августа 2020

Ciao, это простой пример c, но он дает вам представление о том, как выделять текст при вводе. Функция createSelection делает маг c. При передаче input reference, start и end позиций, которые вы хотите выбрать, при нажатии клавиши ввода будет выбран месяц.

<!DOCTYPE html>
<html>
<body>

<h3>Focus on input then click Enter</h3>

<input type="text" id="myText" value="07/05/2020">

<p id="demo"></p>

<script>
var input = document.getElementById("myText");
input.addEventListener("keyup", function(event) {
  if (event.keyCode === 13) {
   event.preventDefault();
   createSelection(input, 3, 5);
  }
});

function createSelection(field, start, end) {
    if( field.createTextRange ) {
      var selRange = field.createTextRange();
      selRange.collapse(true);
      selRange.moveStart('character', start);
      selRange.moveEnd('character', end);
      selRange.select();
      field.focus();
    } else if( field.setSelectionRange ) {
      field.focus();
      field.setSelectionRange(start, end);
    } else if( typeof field.selectionStart != 'undefined' ) {
      field.selectionStart = start;
      field.selectionEnd = end;
      field.focus();
    }
  }
</script>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...