我正在尝试从文本区域中提取确切的选择和光标位置。与往常一样,在大多数浏览器中容易的事情在 IE 中却并不容易。
我正在使用这个:
var sel=document.selection.createRange();
var temp=sel.duplicate();
temp.moveToElementText(textarea);
temp.setEndPoint("EndToEnd", sel);
selectionEnd = temp.text.length;
selectionStart = selectionEnd - sel.text.length;
99% 的情况下都有效。问题是TextRange.text
不返回前导或尾随换行符。因此,当光标是段落后的几个空行时,它会在前一段的末尾产生一个位置 - 而不是实际的光标位置。
eg:
the quick brown fox| <- above code thinks the cursor is here
| <- when really it's here
我能想到的唯一解决方法是在选择之前和之后临时插入一个字符,抓取实际选择,然后再次删除这些临时字符。这是一个 hack,但在快速实验中看起来它会起作用。
但首先我想确定没有更简单的方法。
我正在添加另一个答案,因为我的上一个答案已经变得有些史诗般了。
这是我认为迄今为止最好的版本:它采用 bobince 的方法(在我的第一个答案的评论中提到)并修复了我不喜欢的两件事,首先是它依赖于偏离文本区域的 TextRanges (从而损害性能),第二,必须选择一个巨大的数字来移动范围边界的字符数。
function getSelection(el) {
var start = 0, end = 0, normalizedValue, range,
textInputRange, len, endRange;
if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
start = el.selectionStart;
end = el.selectionEnd;
} else {
range = document.selection.createRange();
if (range && range.parentElement() == el) {
len = el.value.length;
normalizedValue = el.value.replace(/\r\n/g, "\n");
// Create a working TextRange that lives only in the input
textInputRange = el.createTextRange();
textInputRange.moveToBookmark(range.getBookmark());
// Check if the start and end of the selection are at the very end
// of the input, since moveStart/moveEnd doesn't return what we want
// in those cases
endRange = el.createTextRange();
endRange.collapse(false);
if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
start = end = len;
} else {
start = -textInputRange.moveStart("character", -len);
start += normalizedValue.slice(0, start).split("\n").length - 1;
if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
end = len;
} else {
end = -textInputRange.moveEnd("character", -len);
end += normalizedValue.slice(0, end).split("\n").length - 1;
}
}
}
}
return {
start: start,
end: end
};
}
var el = document.getElementById("your_textarea");
var sel = getSelection(el);
alert(sel.start + ", " + sel.end);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)