Javascript 在输入文本字段中设置光标位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5755826/
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-23 18:43:30  来源:igfitidea点击:

Set cursor position in an input text field

javascriptjquery

提问by Mori

After a lot of search I found the following threads:

经过大量搜索,我发现了以下线程:

define cursor position in form input field

在表单输入字段中定义光标位置

jQuery Set Cursor Position in Text Area

jQuery 在文本区域设置光标位置

Unfortunately in none of the posts a complete form embed code or a real example is given. Now I just don't know how to include nemisj's code (on the first link) or Mark's code (on the second link) into my form:

不幸的是,在所有帖子中都没有给出完整的表单嵌入代码或真实示例。现在我只是不知道如何将 nemisj 的代码(在第一个链接上)或 Mark 的代码(在第二个链接上)包含到我的表单中:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>

  <script>
  $(document).ready(function(){
$("#site").focus(function(){
    if( this.value == this.defaultValue ) {
        $(this).val("http://");
    }
});
  });
  </script>

</head>
<body>
<form action="#" method="post">
<input id="name" type="text" name="name" value="Name" /><br />
<input id="site" type="text" name="mail" value="Website" /><br />
<input type="submit" value="Send"> 
</form>
</body>
</html>

I wonder if someone could kindly help me with this as I'm badly stuck!

我想知道是否有人可以帮助我解决这个问题,因为我被困住了!

Many thanks in advance!

提前谢谢了!

Here's the edited code, but it still doesn't work:

这是编辑后的代码,但它仍然不起作用:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>

  <script>
function setCursor(node,pos){

    var node = (typeof node == "string" || node instanceof String) ? document.getElementById(node) : node;

    if(!node){
        return false;
    }else if(node.createTextRange){
        var textRange = node.createTextRange();
        textRange.collapse(true);
        textRange.moveEnd(pos);
        textRange.moveStart(pos);
        textRange.select();
        return true;
    }else if(node.setSelectionRange){
        node.setSelectionRange(pos,pos);
        return true;
    }

    return false;
}
  $(document).ready(function(){
$("#site").focus(function(){
    if( this.value == this.defaultValue ) {
    $(this).val("http://");

    var node = $(this).get(0);
    setCursor(node,node.value.length);
}
});
  });
  </script>

</head>
<body>
<form action="#" method="post">
<input id="name" type="text" name="name" value="Name" /><br />
<input id="site" type="text" name="mail" value="Website" /><br />
<input type="submit" value="Send"> 
</form>
</body>
</html>  

回答by VoteyDisciple

Inside your <script></script>tag is where your JavaScript goes (although we prefer putting it in a separate file, so that no JavaScript lives on the HTML page itself).

里面的<script></script>标签是你的JavaScript去(尽管我们更喜欢把它在一个单独的文件,所以没有JavaScript的生活在HTML页面本身)。

Inside that, you have a call to $(document).ready(), which passes a function() { ... }. Inside that function is all the code that will be executed when your document has loaded.

在里面,你有一个对 的调用$(document).ready(),它传递了一个function() { ... }. 在该函数中包含在您的文档加载时将执行的所有代码。

Inside thatfunction you have a call to $('#site').focus()which itself provides a function —?this time one that will be called whenever the #siteelement gains focus. And presumably that's where you want to change the cursor position.

函数中,您有一个调用,$('#site').focus()该调用本身提供了一个函数——这一次,只要#site元素获得焦点就会被调用。大概这就是您想要更改光标位置的地方。

So, taking the setCursor function from Set cursor at a length of 14 onfocus of a textboxyou can put that anywhere in your <script></script>and then inside that innermost function of yours you can write:

因此,从Set cursor 中获取 setCursor 函数,长度为 14 onfocus 的文本框,您可以将其放在您的任何位置<script></script>,然后在您最内层的函数中,您可以编写:

if( this.value == this.defaultValue ) {
    $(this).val("http://");

    var node = $(this).get(0);
    setCursor(node,node.value.length);
}

回答by Herms

I think I found the error in your setCursormethod. The moveStartand moveEndmethods expect two arguments, the first being the unit it should use. Also, the end position appears to be relative to the start position. So I think instead of

我想我在你的setCursor方法中发现了错误。该moveStartmoveEnd方法有两个参数,第一个是它应该使用的单元。此外,结束位置似乎是相对于开始位置的。所以我认为而不是

    textRange.moveEnd(pos);
    textRange.moveStart(pos);

you want

你要

    textRange.moveStart('character', pos);
    textRange.moveEnd('character', 0);

See: http://msdn.microsoft.com/en-us/library/ie/ms536623(v=vs.85).aspx

请参阅:http: //msdn.microsoft.com/en-us/library/ie/ms536623(v=vs.85).aspx