2011-05-25 73 views
1

後,我能夠使用這個代碼把重點放在文本回傳後:設置在文本光標位置回傳

ScriptManager.RegisterStartupScript(textBox, textBox.GetType(), "selectAndFocus", "$get('" + textBox.ClientID + "').focus();", true); 

但這種設置光標位置到文本的開始,而不是在最後一個輸入的字符。我試圖通過使用此代碼來解決此問題:

textBox.Attributes.Add("onfocus", "$get('" + textBox.ClientID + "').value = $get('" + textBox.ClientID + "').value;"); 

但是這並不奏效。與以前相同的結果。 我該如何解決這個問題?

我讀過大量的鏈接,this看起來像最好的解決方案,但我一直沒有得到它的工作。

更新:忘了提及該文本框駐留在一個updatepanel內。

UPDATE2,嘗試性解決方案:

string setCaretTo = @"function setCaretTo(obj, pos) { 
    if(obj.createTextRange) { 
     /* Create a TextRange, set the internal pointer to 
      a specified position and show the cursor at this 
      position 
     */ 
     var range = obj.createTextRange(); 
     range.move('character', pos); 
     range.select(); 
    } else if(obj.selectionStart) { 
     /* Gecko is a little bit shorter on that. Simply 
      focus the element and set the selection to a 
      specified position 
     */ 
     obj.focus(); 
     obj.setSelectionRange(pos, pos); 
    } 
}"; 
      ScriptManager.RegisterClientScriptBlock(//anotherunrelated script); 
      ScriptManager.RegisterClientScriptBlock(textBox, textBox.GetType(), "MyScript", setCaretTo, true); 
      ScriptManager.RegisterStartupScript(textBox, textBox.GetType(), "MyStartupScript", "window.onload = function() {obj = window.document.getElementById('"+textBox.ClientID+"');setCaretTo(obj, obj.getAttribute('value').length);}", true);` 

回答

0

This解決了這個問題對我來說:

string setCursorToEndScript = @"function SetCursorToTextEnd(textControlID) 
     { 
      var text = document.getElementById(textControlID); 
      if (text != null && text.value.length > 0) 
      { 
       if (text.createTextRange) 
       { 
        var FieldRange = text.createTextRange(); 
        FieldRange.moveStart('character', text.value.length); 
        FieldRange.collapse(); 
        FieldRange.select(); 
       } 
      } 
     } 
      "; 

string setFocusScript = @"$get('" + textBox.ClientID + "').focus();"; 

      ScriptManager.RegisterClientScriptBlock(textBox, textBox.GetType(), "SetCursorToTextEnd", setCursorToEndScript, true); 
      ScriptManager.RegisterStartupScript(textBox, textBox.GetType(), "selectAndFocus", setFocusScript, true); 

      textBox.Attributes.Add("onfocus", "SetCursorToTextEnd('"+ textBox.ClientID +"');"); 
+0

th selectandFocus函數在哪裏?你能幫我提供一下嗎? – 2012-07-25 12:40:46

1

使用setCaretTo功能從你提供我添加了以下JS鏈接:

window.onload = function() { 
    obj = window.document.getElementById('myTextBox'); 
    setCaretTo(obj, obj.getAttribute('value').length); 
} 

這將其設置爲最後一個字符。

+0

感謝,打算儘快嘗試一下。 – 2011-05-26 06:43:23

+0

仍然沒有得到它的工作。用更多信息更新原始帖子。 – 2011-05-26 07:13:22