87,997
社区成员




<textarea id="txt1" style="width:960px;" rows="20" cols="10" onkeyup="this.setAttribute('st',getCaret(this))" onclick="this.setAttribute('st',getCaret(this))"></textarea>
<br /><input type="button" onclick="getInputPos()" value="获取输入位置"/>
<script>
function getInputPos() {
var t = document.getElementById('txt1'), st = t.getAttribute('st'), v = t.value;
var row = -1, col = -1;
if (st != null) {
st = parseInt(st, '');
v = v.substring(0, st);
if (v == '') { row = 1; col = 0 }
else {
row = v.match(/\n/g);
row = row ? row.length + 1 : 1;
var arr = v.split('\n');
col = arr[arr.length - 1].length;
}
}
alert('行:' + row + '\n列:' + col);
}
function getCaret(node) {
if (node.selectionStart) {
return node.selectionStart;
} else if (!document.selection) {
return 0;
}
var c = "\001",
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;
}
</script>