考虑以下代码:(Live demo here - Open in Internet Explorer 7 or 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()
功能取自here。
出于某种原因,单击<div>
时,结果始终为:
Start: 0, End: 0
任何想法如何解决?
答案 0 :(得分:4)
问题是在<div>
函数执行之前单击getInputSelection()
会失去对textarea的关注。有两种选择:
mousedown
事件代替:http://jsfiddle.net/RbSLw/13/或<div>
无法选择(通过在IE中添加unselectable="on"
属性来完成):http://jsfiddle.net/RbSLw/14/。答案 1 :(得分:2)
您的问题是由资源管理器引起的。单击某个按钮时,焦点不会从输入字段中丢失,但是当您单击它div
时,它将被删除,因此不再选择所选文本。
你想要做的是找到一种方法来解决这个问题,方法是强制点击div以不从input
移除焦点。
您可能最好只是在每次更改时保存起始值和结束值,这样当您单击它们时,无论是否选中它都无关紧要。
希望这有助于:)