聚焦输入框加载

Cod*_*x73 89 html javascript xhtml dom

如何在页面加载时将光标聚焦在特定的输入框上?

是否可以保留初始文本值并将光标放在输入的末尾?

<input type="text"  size="25" id="myinputbox" class="input-text" name="input2" value = "initial text" />
Run Code Online (Sandbox Code Playgroud)

jes*_*vin 159

你的问题分为两部分.

1)如何将输入集中在页面加载上?

您只需将autofocus属性添加到输入中即可.

<input id="myinputbox" type="text" autofocus>
Run Code Online (Sandbox Code Playgroud)

但是,并非所有浏览器都支持此功能,因此我们可以使用javascript.

window.onload = function() {
  var input = document.getElementById("myinputbox").focus();
}
Run Code Online (Sandbox Code Playgroud)

2)如何将光标放在输入文本的末尾?

这是一个非jQuery解决方案,其中包含来自另一个SO答案的一些借用代码.

function placeCursorAtEnd() {
  if (this.setSelectionRange) {
    // Double the length because Opera is inconsistent about 
    // whether a carriage return is one character or two.
    var len = this.value.length * 2;
    this.setSelectionRange(len, len);
  } else {
    // This might work for browsers without setSelectionRange support.
    this.value = this.value;
  }

  if (this.nodeName === "TEXTAREA") {
    // This will scroll a textarea to the bottom if needed
    this.scrollTop = 999999;
  }
};

window.onload = function() {
  var input = document.getElementById("myinputbox");

  if (obj.addEventListener) {
    obj.addEventListener("focus", placeCursorAtEnd, false);
  } else if (obj.attachEvent) {
    obj.attachEvent('onfocus', placeCursorAtEnd);
  }

  input.focus();
}
Run Code Online (Sandbox Code Playgroud)

这是一个如何用jQuery完成这个的例子.

<input type="text" autofocus>

<script>
$(function() {
  $("[autofocus]").on("focus", function() {
    if (this.setSelectionRange) {
      var len = this.value.length * 2;
      this.setSelectionRange(len, len);
    } else {
      this.value = this.value;
    }
    this.scrollTop = 999999;
  }).focus();
});
</script>
Run Code Online (Sandbox Code Playgroud)

  • 建议的第一个代码块实际上也将光标放在现有值的末尾,它运行良好.我很感激你的帮助. (3认同)

Dav*_*oun 45

只是提醒 - 现在您可以使用不带JavaScript的HTML5来支持它的浏览器:

<input type="text" autofocus>
Run Code Online (Sandbox Code Playgroud)

您可能希望从此开始并使用JavaScript构建它以为旧版浏览器提供后备.

  • 你没错,这不是一个完整的解决方案.但这确实解决了一些问题(onload autofocus和占位符文本). (2认同)

Nas*_*din 10

$(document).ready(function() {
    $('#id').focus();
});
Run Code Online (Sandbox Code Playgroud)