考虑以下代码:(此处为现场演示 - 在 Internet Explorer 7 或 9 中打开)
HTML:
<textarea>Hello Stack Overflow</textarea>
<input class="a" type="button" value="Click here does the job" />
<div class="a">But clicking here not :(</div>
JS:
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};
}
function getselection() {
var selectedText = getInputSelection($("textarea")[0]);
var start = selectedText.start;
var end = selectedText.end;
alert("Start: " + start + ", End: " + end);
}
$(".a").click(getselection);
该getInputSelection()
函数取自这里。
出于某种原因,当<div>
单击 时,结果总是:
Start: 0, End: 0
任何想法如何解决这个问题?