考虑以下代码:( 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
有什么解决办法吗?
最佳答案
问题是点击 <div>
在 getInputSelection()
之前失去对文本区域的关注函数执行。有两种选择:
- 要么使用
mousedown
事件改为:http://jsfiddle.net/RbSLw/13/ , 或 - 制作
<div>
不可选择(通过在 IE 中添加unselectable="on"
属性来完成):http://jsfiddle.net/RbSLw/14/ .
关于javascript - 为什么在单击按钮时从 textarea 中获取文本选择有效,但在单击 "div"时无效(在 Internet Explorer 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7190606/