2011-09-13 61 views
3

我正在升級一些適用於IE的Javascript。但是,我遇到了一些問題。如何在光標所在處插入一些文字?

繼承人的IE代碼:

var range = document.getElementById('text').contentWindow.window 
       .document.getElementById('Content').createTextRange(); 
var textObj = document.getElementById('text').contentWindow.window 
       .document.getElementById('Content'); 

var textFieldValue = theSmile; 
if (range && textObj.CursorPos) { 
    var CursorPos = textObj.CursorPos; 
    CursorPos.text = CursorPos.text.charAt(CursorPos.text.length - 1) 
           == ' ' ?' ' + textFieldValue : textFieldValue; 
} else { 
    textObj.value = textFieldValue; 
} 

我試着CreateRange更換CreateTextRange對非IE瀏覽器,但是這並沒有幫助。用這樣的代碼:

var range; 
var textObj; 
var iframeEl = document.getElementById('text'); 
if (iframeEl.contentDocument) { // DOM 
    range = iframeEl.contentDocument.getElementById('Content').createRange; 
    textObj= iframeEl.contentDocument.getElementById('Content'); 
} else if (iframeEl.contentWindow) { // IE win 
    range = iframeEl.contentWindow.document.getElementById('Content') 
                  .createTextRange; 
    textObj= iframeEl.contentWindow.document.getElementById('Content'); 
} 

回答

9

這裏是一個函數插入文本在textarea或文本輸入,這是它看起來你有。它適用於所有的主流瀏覽器:

function insertTextAtCursor(el, text) { 
    var val = el.value, endIndex, range, doc = el.ownerDocument; 
    if (typeof el.selectionStart == "number" 
      && typeof el.selectionEnd == "number") { 
     endIndex = el.selectionEnd; 
     el.value = val.slice(0, endIndex) + text + val.slice(endIndex); 
     el.selectionStart = el.selectionEnd = endIndex + text.length; 
    } else if (doc.selection != "undefined" && doc.selection.createRange) { 
     el.focus(); 
     range = doc.selection.createRange(); 
     range.collapse(false); 
     range.text = text; 
     range.select(); 
    } 
} 

可以按如下方式使用它:

var iframeWin = document.getElementById('text').contentWindow; 
var textObj = iframeWin.document.getElementById('Content'); 

insertTextAtCursor(textObj, "foo"); 
相關問題