我有一個場景,我需要將光標放在文本區域上,然後單擊相同頁面上的樹視圖節點以將選定節點的文本放入我的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並將其光標位置保存到隱藏字段中,所以當焦點移動到其他控件時,我將隱藏字段以獲取文本區域的光標位置。我將在稍後發佈,同時如果有人有一個好主意,那麼請分享。
預先感謝您
我用'。對( '事件的內容',...)'(或.focusout(),這是相同的)保存選擇位置,這在焦點丟失之前被調用。此外,事件泡沫,所以你可以在父元素中捕捉它(模糊不泡)。 – Silentdrummer