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

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

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

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

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

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


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

提前谢谢了!

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

       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); } }); });    


在您的标记内部是您的JavaScript所在(虽然我们更喜欢将它放在一个单独的文件中,因此HTML页面本身不会存在任何JavaScript)。

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

函数内部您可以调用$('#site').focus()本身提供了一个函数 – 这次只要#site元素获得焦点就会被调用。 并且可能是您想要更改光标位置的位置。

因此,将Set cursor的setCursor函数设置为文本框的14 onfocus长度,你可以将它放在中的任何位置,然后在你的最里面的函数中你可以写:

 if( this.value == this.defaultValue ) { $(this).val("http://"); var node = $(this).get(0); setCursor(node,node.value.length); } 

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

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

你要

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

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