为了省事,少量位置用了jquery 改原生JS也很方便,谁需要就请自己修改了。
欢迎各位路过高人拍板,欢迎各位留言提供改进代码。
又改进 兼容了Chrome 下面的代码已修改成最新版
上源码了
代码如下:
var result = 0;
if (!document.selection) { //非IE浏览器
var thisTagName = null;
if ($(element).attr("tagName") != "TEXTAREA" && $(element).attr("tagName") != "INPUT") {
if ($(element).attr("tagName") == "DIV" && $(element).attr("contenteditable") == "true") {
thisTagName = window.getSelection().anchorNode.parentElement.tagName;
} //出自http://www.cnblogs.com/ahjesus 尊重作者辛苦劳动成果,转载请注明出处,谢谢!
else {
thisTagName == null;
}
}
else {
if ($(element).attr("tagName") == "INPUT" && $(element).attr("type") == "text") {
thisTagName = window.getSelection().anchorNode.tagName;
}
else {
console.log(window.getSelection());
thisTagName = window.getSelection().anchorNode.tagName;
}
}
console.log(thisTagName);
if (thisTagName == "TEXTAREA" || thisTagName == "INPUT" || (thisTagName=="BODY"&&OsObject == "Chrome")) {
result = element.selectionStart
} //出自http://www.cnblogs.com/ahjesus 尊重作者辛苦劳动成果,转载请注明出处,谢谢!
else if (thisTagName != null) {
if (thisTagName == element.tagName) {
if (window.getSelection().anchorNode.textContent == $(element).text()) {
result = window.getSelection().anchorOffset;
}
else {
var currentIndex = window.getSelection().anchorOffset;
var txt = "";
var txtoo = window.getSelection().anchorNode.previousSibling;
while (txtoo != null) {
txt += txtoo.textContent;
txtoo = txtoo.previousSibling;
} //出自http://www.cnblogs.com/ahjesus 尊重作者辛苦劳动成果,转载请注明出处,谢谢!
result = txt.trim().length + currentIndex;
}
}
else {
var currentIndex = window.getSelection().anchorOffset;
var txt = "";
var txtoo = window.getSelection().anchorNode.parentElement.previousSibling;
while (txtoo != null) {
txt += txtoo.textContent;
txtoo = txtoo.previousSibling;
}
result = txt.trim().length + currentIndex;
}
} //出自http://www.cnblogs.com/ahjesus 尊重作者辛苦劳动成果,转载请注明出处,谢谢!
else {
return 0;
}
} else { //IE
var rng;
if ($(element).attr("tagName") == "TEXTAREA" || ($(element).attr("tagName") == "INPUT" && $(element).attr("type") == "text") || ($(element).attr("tagName") == "DIV" && $(element).attr("contenteditable") == "true")) {
element.focus();
rng = document.selection.createRange();
rng.moveStart('character', -element.innerText.length);
var text = rng.text;
for (var i = 0; i < element.innerText.length; i++) {
if (element.innerText.substring(0, i + 1) == text.substring(text.length - i - 1, text.length)) {
result = i + 1;
}
}
} //出自http://www.cnblogs.com/ahjesus 尊重作者辛苦劳动成果,转载请注明出处,谢谢!
else {
return 0;
}
}
return result;
}
function getValue(element) {
var pos = getPosition(element);
document.getElementById("pnum").value = pos;
}
script>