2012-11-05 49 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); 
     }); 
    })(); 

希望,這將是現在的工作

相關問題