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

Mor*_*ori 16 javascript jquery

经过大量搜索后,我找到了以下主题:

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

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

不幸的是,在所有帖子中都没有给出完整的表单嵌入代码或真实示例.现在我只是不知道如何在我的表单中包含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>
Run Code Online (Sandbox Code Playgroud)

我想知道是否有人可以帮助我,因为我被困住了!

提前谢谢了!

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

<!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>  
Run Code Online (Sandbox Code Playgroud)

Vot*_*ple 4

标签内<script></script>是 JavaScript 所在的位置(尽管我们更喜欢将其放在单独的文件中,这样 HTML 页面本身就不会存在 JavaScript)。

\n\n

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

\n\n

在该函数内部,您有一个调用$(\'#site\').focus(),它本身提供了一个函数 \xe2\x80\x94\xc2\xa0 这一次,每当元素获得焦点时就会调用该函数#site。想必这就是您想要更改光标位置的地方。

\n\n

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

\n\n
if( this.value == this.defaultValue ) {\n    $(this).val("http://");\n\n    var node = $(this).get(0);\n    setCursor(node,node.value.length);\n}\n
Run Code Online (Sandbox Code Playgroud)\n