Mis*_*hko 3 javascript jquery textarea textselection internet-explorer-7
我尝试了jquery-fieldselection插件来获取textarea中的选定文本.
它在Firefox和Chrome中运行良好,但在Internet Explorer 7中运行不正常.
我使用这样的getSelection()方法:
textarea.getSelection();
Run Code Online (Sandbox Code Playgroud)
当textarea中的12345文本被选中并且所有这些文本被选中时,Firefox和Chrome将返回:
start: 0 // Correct!
end: 5
Run Code Online (Sandbox Code Playgroud)
Internet Explorer 7返回时:
start: 5 // Why ??
end: 5
Run Code Online (Sandbox Code Playgroud)
我正在寻找使用jQuery的跨浏览器解决方案.
只是看了一下tthelibrary,它的行为与IE不同,因为它不支持现代浏览器所做的一些方法..可能是代码不完美..
使用以下方法:
function getInputSelection(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
};
}
Run Code Online (Sandbox Code Playgroud)
如何使用它:
你需要textarea的dom对象..因此:
var textArea= $("textarea")[0] or getElementbyId("textareaid");
var selectedText=getInputSelection(textArea);
var start=selectedText.start;
var end=selectedText.end;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6955 次 |
| 最近记录: |