在输入之间切换时如何防止突出显示所有文本?

sti*_*til 5 html javascript

我有许多需要重复填写的输入字段,因此我通常用它Tab来浏览表单。

字段具有需要前置的默认后缀值。当我通过鼠标单击将焦点集中在输入上时,它会按预期工作。

但是,当我在输入之间切换时,它会选择所有文本,这在我的情况下是不良行为。

看看这个:

function setCaretPosition(elem, caretPos) {
  if (elem == null) return;
  if (elem.createTextRange) {
    var range = elem.createTextRange();
    range.move('character', caretPos);
    range.select();
  } else if (elem.selectionStart) {
    elem.focus();
    elem.setSelectionRange(caretPos, caretPos);
  } else {
    elem.focus();
  }
}

$(document).ready(function() {
  $('input').focus(function() {
    setCaretPosition(this, 0);
  });
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input1" value=" km/h" />
<input type="text" id="input2" value=" kg" />
Run Code Online (Sandbox Code Playgroud)

  • 当您在任何输入内部单击时,插入符号会设置在开头。
  • 当您Tab在输入之间插入符号时,未设置。相反,整个输入内容都会突出显示。

使用选项卡导航时如何防止文本输入突出显示其内容?

setTimeout我更喜欢不使用(如果可能的话)的答案。

Min*_*ess 5

在 Chrome 和 Explorer 上(不适用于 Edge 和 Firefox),只需:

<input type="text" value=" km/h" onfocus="this.setSelectionRange(this.value.length, this.value.length)"/>
<input type="text" value=" kg" onfocus="this.setSelectionRange(this.value.length, this.value.length)"/>
Run Code Online (Sandbox Code Playgroud)

在 Firefox 和 Chrome 上(不适用于 Edge 和 Explorer)

jQuery.fn.putCursorAtEnd = function() {
  return this.each(function() {
    // Cache references
    var $el = $(this), el = this;
    
    // Timeout seems to be required for Firefox
    setTimeout(function() {
      el.setSelectionRange($el.val().length, $el.val().length);
    }, 0);
  });
};

var searchInput = $("input");

searchInput.on("focus", function() { // could be on any event
    searchInput.putCursorAtEnd()
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value=" km/h" />
<input type="text" value=" kg" />
Run Code Online (Sandbox Code Playgroud)