2013-10-30 94 views
0

我做了以下功能將消息(msg)插入到文本字段中。在文本字段中插入文本後的焦點光標

插入文本後,光標需要位於輸入的msg的最後一個字符之後。文本字段已包含一些文本。

當我插入消息時,光標會聚焦在味精末尾附近的某處,但肯定不會在最後一個字符後面聚焦。似乎有些角色不會被.length計算在內?

 function insertAtCursor(msg) { 
      var textArea = document.getElementsByName("message")[0]; 
      textArea.value = textArea.value.substr(0, textArea.selectionStart) + msg +  textArea.value.substr(textArea.selectionEnd); 
      var endMsgPos = textArea.value.lastIndexOf(msg) + msg.length; 
      textArea.setSelectionRange(endMsgPos, endMsgPos); 
    } 

回答

1

沒有必要爲textArea.value.lastIndexOf(msg)

function insertAtCursor(msg) { 
    var textArea = document.getElementsByName("message")[0]; 
    var selStart = textArea.selectionStart, val = textArea.value; 
    textArea.value = val.slice(0, selStart) + msg + 
        val.slice(textArea.selectionEnd); 
    var endMsgPos = selStart + msg.length; 
    textArea.setSelectionRange(endMsgPos, endMsgPos); 
} 
+0

的感謝!這絕對有效。但是,當我輸入更長的文本時,光標不會留在msg文本之後,而是向前跳過幾個字符到其下面的文本中。這可能是因爲味精文本包含/ n或特殊字符? (URL) – Bunker

+0

@Bunker:哪個瀏覽器? –

+0

Chrome,它適用於Chrome擴展程序:-) – Bunker

1

首先,如果您嘗試使用textArea.selectionStart因爲它使用了不同的API,你必須與IE 8的問題。

其次lastIndexOf在您的代碼中會出現奇怪的現象,如果插入符號在字符串的尾部,並且在末尾存在msg的值。

試試這個:

function insertAtCursor(msg) { 
    var e = document.getElementsByName('message')[0], 
    length = msg.length, val = e.value; 
    /* mozilla/dom 3.0 */ 
    if ('selectionStart' in e){ 
     var partial = val.slice(0, e.selectionStart) + msg; 
     e.value = partial + val.slice(e.selectionEnd); 
     var end = partial.length; 
     e.setSelectionRange(end, end); 
    } 
    /* exploder */ 
    if (document.selection){ 
     e.focus(); 
     document.selection.createRange().text = msg; 
    } 
    } 

演示是在這裏:http://jsbin.com/UnOBUbU/6

相關問題