With Firefox, Safari (and other Gecko based browsers) you can easily use textarea.selectionStart, but for IE that doesn't work, so you will have to do something like this:(使用Firefox,Safari(以及其他基于Gecko的浏览器),您可以轻松使用textarea.selectionStart,但对于不起作用的IE,您必须执行以下操作:)
function getCaret(node) {
if (node.selectionStart) {
return node.selectionStart;
} else if (!document.selection) {
return 0;
}
var c = "01",
sel = document.selection.createRange(),
dul = sel.duplicate(),
len = 0;
dul.moveToElementText(node);
sel.text = c;
len = dul.text.indexOf(c);
sel.moveStart('character',-1);
sel.text = "";
return len;
}
( complete code here )(( 这里完整代码 ))
I also recommend you to check the jQuery FieldSelection Plugin, it allows you to do that and much more...(我还建议你检查jQuery FieldSelection插件,它允许你这样做以及更多......)
Edit: I actually re-implemented the above code:(编辑:我实际上重新实现了上面的代码:)
function getCaret(el) {
if (el.selectionStart) {
return el.selectionStart;
} else if (document.selection) {
el.focus();
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = el.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
return rc.text.length;
}
return 0;
}
Check an example here .(点击这里查看示例。) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…