Bra*_*son 7 javascript internet-explorer dom
我正在尝试从textarea中提取确切的选择和光标位置.像往常一样,大多数浏览器中的简单操作都不在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;
Run Code Online (Sandbox Code Playgroud)
其中99%的时间都有效.问题是TextRange.text不返回前导或尾随换行符.因此,当光标在段落之后是几个空行时,它会在前一段的末尾产生一个位置 - 而不是实际的光标位置.
例如:
the quick brown fox| <- above code thinks the cursor is here
| <- when really it's here
Run Code Online (Sandbox Code Playgroud)
我能想到的唯一解决方法是在选择之前和之后临时插入一个字符,抓取实际选择,然后再次删除那些临时字符.这是一个黑客,但在一个快速实验看起来它会起作用.
但首先,我想确定没有更简单的方法.
Tim*_*own 12
我正在添加另一个答案,因为我之前的答案已经有点史诗了.
这是我认为最好的版本:它需要bobince的方法(在我的第一个答案的评论中提到)并修复了我不喜欢它的两件事,首先它依赖于杂散在textarea之外的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);
Run Code Online (Sandbox Code Playgroud)