2012-11-05 48 views
2

可能重复:
jQuery Set Cursor Position in Text Area将光标置于文本输入的左侧

当与文本输入被聚焦,光标开始于对所述文本的末尾右边。如何让光标位于焦点左侧?

我见过使用“setCursor”的例子,但是我得到一个setCursor没有定义的错误。

<input type="text" class="myInput"> 
    Tabbing into this should put my cursor at the left! 
</input> 

setCursor抛出一个错误,说明它未定义。

$(".myInput").focus(function(){ 
    var node = $(this); 
    setCursor(node, 0); 
}); 
+0

已经很接近了,但这个问题的答案是从2009年因此有可能是更清洁的方式,现在来处理它: ) –

+0

_“当有文本输入焦点时,光标从右侧文本的末尾开始”_ - 通常不是在选项卡中选择输入中的所有文本,或者将光标完全放入如果使用鼠标点击的地方? – nnnnnn

+3

@DonnyP事实上,我认为即使使用HTML5,也没有什么变化。 – AndreKR

回答

3

试试这个..

<input type="text" class="myInput" value="Tabbing into this should put my cursor at the left!" /> 

(function(){ 
     jQuery.fn.setSelection = function(selectionStart, selectionEnd) { 
      if(this.length == 0) return this; 
      input = this[0]; 

      if (input.createTextRange) { 
       var range = input.createTextRange(); 
       range.collapse(true); 
       range.moveEnd('character', selectionEnd); 
       range.moveStart('character', selectionStart); 
       range.select(); 
      } else if (input.setSelectionRange) { 
       input.focus(); 
       input.setSelectionRange(selectionStart, selectionEnd); 
      } 

      return this; 
     } 
     jQuery.fn.setCursorPosition = function(position){ 
      if(this.length == 0) return this; 
      return $(this).setSelection(position, position); 
     } 
     $(".myInput").focus(function(){ 
      $(this).setCursorPosition(0); 
     }); 
    })(); 

希望,这将是现在的工作

相关问题