假设有一个常规的<input type=text>
其中包含数据的文本框。
是否可以(通过 JavaScript)检测文本框中文本光标的位置?
我能够检测向左箭头或向右箭头按键事件 - 但如何检测光标位置?
为什么我需要这个:
我在这方面做了很多工作。以下内容适用于所有主要浏览器(包括 IE 6)的文本<input>
s and <textarea>
s 并且适用于所有情况,包括当存在前导空格和尾随空格时(这是许多解决方案,包括 a-tool 失败的地方)。这个问题中的这段代码有一些背景:IE 的 document.selection.createRange 不包含前导或尾随空白行
您还可以获取以下内容作为我编写的尚未记录的 jQuery 输入/文本区域选择插件的一部分:http://code.google.com/p/rangyinputs/
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
};
}
var el = document.getElementById("your_input");
var sel = getInputSelection(el);
alert(sel.start + ", " + sel.end);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)