加载时焦点输入框 [英] Focus Input Box On Load

查看:24
本文介绍了加载时焦点输入框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can the cursor be focus on a specific input box on page load?

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

Is it posible to retain initial text value as well and place cursor at end of input?

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

推荐答案

您的问题有两个部分.

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

您可以将 autofocus 属性添加到输入中.

You can just add the autofocus attribute to the input.

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

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

However, this might not be supported in all browsers, so we can use javascript.

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

2) 如何将光标置于输入文本的末尾?

这是一个非 jQuery 解决方案,其中有一些从 另一个 SO 答案 中借用的代码.

Here's a non-jQuery solution with some borrowed code from 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 完成此任务的示例.

Here's an example of how I would accomplish this with 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>

这篇关于加载时焦点输入框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆