【发布时间】:2012-10-27 13:40:33
【问题描述】:
我有一个场景,我需要将光标放在文本区域,然后单击同一页面上的树视图节点,以将节点的文本选择到我在单击树节点之前放置光标的文本区域。
我得到了很多关于堆栈溢出的答案,包括以下,
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 和 Chrome 在上述解决方案中运行良好,但如果焦点移动到其他控件,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 并将其光标位置保存到隐藏字段中,因此当焦点移动到其他控件时,我将有隐藏字段来获取文本区域的光标位置。我稍后会在这里发布,同时如果有人有什么好主意,请分享。
提前谢谢你
【问题讨论】:
标签: javascript jquery internet-explorer textarea