Javascript 将光标移动到输入字段的开头?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2127221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:51:31  来源:igfitidea点击:

move cursor to the beginning of the input field?

javascriptjquery

提问by ajsie

when you click on 'Ask question' here in Stackoverflow you see a text "What's your programming question? Be descriptive."

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

i want the same thing and all i need for that is to move my cursor to the beginning of the text field. how do i do that with jquery?

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

采纳答案by Mic

May be that is an overkill, but these functions are helpful to select a portion of an input field.

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

The code below place the cursor to the first char of the second field.

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

<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>

回答by Sejanus

You can use focus() method. If I recall jQuery, its like this: $("#question_input_field_id").focus(); (If I got your question right)

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

Update: Setting cursor at the beginning:

更新:在开头设置光标:

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

回答by Reigel

if you look into the source code of stackoverflow > ask question, you will find this:

如果您查看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>

what really is happening is that a CSS code made the <span class="edit-field-overlay">move over the top of input box and show hide when needed... and just do what Sejanus' suggested.

真正发生的事情是,CSS 代码<span class="edit-field-overlay">移动到输入框的顶部并在需要时显示隐藏……然后按照 Sejanus 的建议进行操作。

回答by Yoky

 $('#txtYourTextBox').blur(function () { 
    var val = $("#txtYourTextBox").val();
    $("#txtYourTextBox").val('');
    setTimeout(function () { $("#txtYourTextBox").val(val); }, 20);
});