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

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

<input type="text"  size="25" id="myinputbox" class="input-text" name="input2" value = "initial text" />

推荐答案

你的问题有两个部分.

1) How to focus an input on page load?

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

<input id="myinputbox" type="text" autofocus>

但是,并不是所有的浏览器都支持这一点,所以我们可以使用javascript.

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

2) How to place cursor at the end of the input text?

下面是一个非jQuery解决方案,其中包含一些borrow 自another SO answer的代码.

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();
}

下面是我如何使用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>

Html相关问答推荐

迪夫导航栏的一些组件显示在导航栏之外,有人能帮助我解决这个问题吗?

悬停时放大人物:不要增加其周围边界的大小

放大缩小标题在外面的图像

附加点的列表样式

如何影响flex项目中的flex-gap收缩顺序和文本换行顺序?

SVG动画只有在打开S开发工具的浏览器时才开始播放

渐变进度条位置

如何更改Django中的默认按钮?

带下划线的文本应该有延长的下划线,以使其图像悬停

如何在css中在span中绘制圆弧?

带有图像的虚线边框

水平填充容器内的空间

在锥形渐变进度条内创建空白的问题

在 vscode 中找不到 htmltagwrap 命令

为什么在使用src与srcdoc时 iframe 内容高度呈现不同?

是否可以将文本添加到表格边框?

如何为某些行具有 rowspan 的表的每个奇数行着色

弹出窗口溢出溢出:自动,我不明白为什么

左右图像,响应页面大小并居中

AWS SES:如何正确使用 CSS