Разделить ввод на отдельные поля - PullRequest
0 голосов
/ 18 января 2020

Я хочу разделить ввод на отдельные символы / поля git, как на этой фотографии

В идеале, ввод значения di git приведет вас к следующему вводу поле и каждый из них будет выделен отдельно с активной рамкой. Я могу использовать комбинацию стилей и Javascript для достижения sh этого.

Любое понимание будет очень полезным! Заранее спасибо.

1 Ответ

0 голосов
/ 18 января 2020

Вот один из способов реализации этого шаблона:

<div class="digits">
  <input type="text" maxlength="1" name="digit1" />
  <input type="text" maxlength="1" name="digit2" />
  <input type="text" maxlength="1" name="digit3" />
  <input type="text" maxlength="1" name="digit4" />  
</div>
input {
  font-size: 2rem;
  width: 1.5rem;
  text-align: center;
}
input:focus {
  border: 2px solid yellowgreen;
  outline: none;
}
// Listen on the 'input' event inside the .digits area:
document.querySelector(".digits").addEventListener("input", function(e){

  // Exclude non-numeric characters from input:
  e.target.value = e.target.value.replace(/[^0-9]/g,'');

  // If the input value is filled and there is a neighbouring element that is input, then focus on that element:
  if ( e.target.value !== "" && e.target.nextElementSibling && e.target.nextElementSibling.nodeName === "INPUT" ){

    e.target.nextElementSibling.focus();

  }

});

2) Если вы хотите, чтобы входные значения были обновлены, когда они уже заполнены:

<div class="digits">
  <input type="text" name="digit1" />
  <input type="text" name="digit2" />
  <input type="text" name="digit3" />
  <input type="text" name="digit4" />  
</div>
document.querySelector(".digits").addEventListener("input", function(e){
  e.target.value = e.data.replace(/[^0-9]/g,'');
  if ( e.target.value !== "" && e.target.nextElementSibling && e.target.nextElementSibling.nodeName === "INPUT" ){
    e.target.nextElementSibling.focus();
  } 
});

Codepen (содержит некоторые дополнительные проверки и эффекты)

...