2012-11-07 79 views
3

我有一個場景,我需要將光標放在文本區域上,然後單擊相同頁面上的樹視圖節點以將選定節點的文本放入我的textarea中,在點擊樹節點之前放置光標。問題在將文本插入光標位置的文本區域時

我上堆棧溢出很多答案如下,包括

Inserting text in textarea at cursor position if cursor placed else text should append at last in IE

Inserting text after cursor position in text areа

Insert text into textarea with jQuery

How to insert text at the current caret position in a textarea

Inserting text at cursor in a textarea, with Javascript

How do I insert some text where the cursor is?

FF和鉻正常工作與上述解決方案,但IE 8或更低版本失敗(不與IE9檢查),如果焦點移動到其他一些控制。

有以下或類似的實現IE瀏覽器在幾乎所有的帖子:

(function ($) { 
    $.fn.getCursorPosition = function() { 
     var el = $(this).get(0); 
     var pos = 0; 
     if ('selectionStart' in el) { 
      pos = el.selectionStart; 
     } else if ('selection' in document) { 
      el.focus(); 
      var Sel = document.selection.createRange(); 
      var SelLength = document.selection.createRange().text.length; 
      Sel.moveStart('character', -el.value.length); 
      pos = Sel.text.length - SelLength 
     } 
     return pos; 
    } 
})(jQuery); 

注:我們也可以使用if(el.selectionStart || el.selectionStart == '0')代替if ('selectionStart' in el)if(document.selection)代替if ('selection' in document)

但是當焦點在此將失敗先移動到其他控件然後執行它。在我的情況下,當用戶遍歷節點時,焦點將移動到樹節點。

這種情況下是否有解決方案?

我想在文本區域寫onkeyup和onclick並將其光標位置保存到隱藏字段中,所以當焦點移動到其他控件時,我將隱藏字段以獲取文本區域的光標位置。我將在稍後發佈,同時如果有人有一個好主意,那麼請分享。

預先感謝您

回答

2

正如我上面提到我有下面的代碼,使其工作在IE爲好, (也想過只具有替代的onblur這兩個事件,但它並沒有爲工作重點當執行進入我的代碼設置隱藏變量時已經丟失)

以下實施它在我的情況下工作正常。

if ($("#myTextArea").get(0).selectionStart == undefined) { 
    $("#myTextArea").click(function (e) { 
     $("#hdnTextAreaPosition").val($("#myTextArea").getCursorPosition()); 
    }); 
    $("#myTextArea").keyup(function (e) { 
     $("#hdnTextAreaPosition").val($("#myTextArea").getCursorPosition()); 
    }); 
} 

上述事件(KEYUP和點擊)在全局腳本,將在選擇開始的情況下,只有連接是未定義

function getTextAreaCursorPosition() { 
    if ($("#myTextArea").get(0).selectionStart == undefined) { 
     return $("#hdnTextAreaPosition").val(); 
    } 
    else { 
     return $("#myTextArea").getCursorPosition(); 
    } 
} 


function insertToMyTextArea(textToInsert) { 
    $("#myTextArea").focus(); 
    var cursorPosition = getTextAreaCursorPosition(); 
    var myContent = $("#myTextArea").val(); 
    $("#myTextArea").val(myContent.substring(0, cursorPosition) + textToInsert + myContent.substring(cursorPosition)); 
} 

insertToMyTextArea的主要功能是我我正在呼叫點擊樹節點。

如果有其他解決方案可用,而不是有活動,請分享您的觀點。

+0

我用'。對( '事件的內容',...)'(或.focusout(),這是相同的)保存選擇位置,這在焦點丟失之前被調用。此外,事件泡沫,所以你可以在父元素中捕捉它(模糊不泡)。 – Silentdrummer

相關問題