try this:<input value=0123456789 id="txt1"></input>
<input type="button" value="show caret position" onclick="getCaretPos()">
<script>
function getCaretPos()
{
txt1.focus();
// get current selection. Object must have a focus at this time
var currentRange=document.selection.createRange();
var workRange=currentRange.duplicate();// select the whole contents and get 'all' selection
txt1.select();
var allRange=document.selection.createRange();
var len=0;// move current selection to the start of object
// note: we do not use text.length property since it's not equal
// to the caret actual position while(workRange.compareEndPoints("StartToStart",allRange)>0)
{
workRange.moveStart("character",-1);
len++;
}// restore original selection
// it was lost when we did select() thing currentRange.select();// len contains the caret position if no selection
// or selection start point offset if any alert(len);
}
</script>
<input type="button" value="show caret position" onclick="getCaretPos()">
<script>
function getCaretPos()
{
txt1.focus();
// get current selection. Object must have a focus at this time
var currentRange=document.selection.createRange();
var workRange=currentRange.duplicate();// select the whole contents and get 'all' selection
txt1.select();
var allRange=document.selection.createRange();
var len=0;// move current selection to the start of object
// note: we do not use text.length property since it's not equal
// to the caret actual position while(workRange.compareEndPoints("StartToStart",allRange)>0)
{
workRange.moveStart("character",-1);
len++;
}// restore original selection
// it was lost when we did select() thing currentRange.select();// len contains the caret position if no selection
// or selection start point offset if any alert(len);
}
</script>
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货