【问题标题】:move cursor to the beginning of the input field?将光标移动到输入字段的开头?
【发布时间】:2011-01-08 19:00:35
【问题描述】:

当您在 Stackoverflow 中点击此处的“提问”时,您会看到一条文本“您的编程问题是什么?要有描述性。”

我想要同样的东西,我只需要将光标移动到文本字段的开头。我如何用 jquery 做到这一点?

【问题讨论】:

标签: javascript jquery


【解决方案1】:

这可能有点矫枉过正,但这些功能有助于选择输入字段的一部分。

下面的代码将光标放在第二个字段的第一个字符上。

<html>
<head>
    <title>so</title>
</head>
<body>
    <input value="stack" />
    <input value="overflow" />
    <script>
        var inp = document.getElementsByTagName('INPUT')[1];
        if (inp.createTextRange) {
            var part = inp.createTextRange();
            part.move("character", 0);
            part.select();
        } else if (inp.setSelectionRange) {
            inp.setSelectionRange(0, 0);
        }
        inp.focus();
    </script>
</body>
</html>

【讨论】:

  • 值得注意的是,如果您不支持 Internet Explorer,则可以省略此答案中的 createTextRange
【解决方案2】:

您可以使用 focus() 方法。如果我记得 jQuery,它是这样的: $("#question_input_field_id").focus(); (如果我没看错你的问题)

更新: 在开头设置光标:

$("#question_input_field_id").focus();
$("#question_input_field_id").get(0).setSelectionRange(0,0);

【讨论】:

  • 如果我在文本字段中有文本,那么如果我使用焦点,光标将在文本之后的文本字段末尾。我希望它在正文之前的开头。
  • 知道了。更新了我原来的答案。适用于 Firefox(即 Gecko 浏览器),不确定其他浏览器。
  • 您不能将 jQuery 对象与 setSelectionRange 一起使用。这将起作用: $("#question_input_field_id")[0].setSelectionRange(0,0);
  • @Andre 刚刚在此评论线程中发布了正确答案。
  • setSelectionRange 对我来说是未定义的
【解决方案3】:

如果你查看stackoverflow的源代码>提问,你会发现:

<table style="width:668px"> 
     <tr> 
         <td style="width:50px"><label for="title">Title</label></td> 
         <td style="padding-left:5px"><input id="title" name="title" type="text" maxlength="300" tabindex="100" style="width:610px" value=""> 
              <span class="edit-field-overlay">What's your programming question? Be descriptive.</span> 
         </td> 
     </tr> 
</table>

真正发生的是 CSS 代码使 &lt;span class="edit-field-overlay"&gt; 移动到输入框的顶部并在需要时显示隐藏...并按照 Sejanus 的建议进行操作。

【讨论】:

  • 哈哈..老实说,这很“蹩脚”......但好吧......它奏效了:)
  • 呵呵..有时候,事情很容易...如果您只是不忽略问题...您只需要欺骗眼睛.. :)
  • +1 我发现这个特殊的魔法正是我所需要的。
【解决方案4】:
 $('#txtYourTextBox').blur(function () { 
    var val = $("#txtYourTextBox").val();
    $("#txtYourTextBox").val('');
    setTimeout(function () { $("#txtYourTextBox").val(val); }, 20);
});

【讨论】:

  • 看起来这段代码缓存了输入的值,清除它,然后重新应用相同的值。每次焦点离开输入时,所有这些都会发生。我不确定这应该如何回答这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-26
  • 2011-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-24
相关资源
最近更新 更多