Skip to content

Instantly share code, notes, and snippets.

@wjzhangq
Created November 2, 2010 04:12
Show Gist options
  • Save wjzhangq/659253 to your computer and use it in GitHub Desktop.
Save wjzhangq/659253 to your computer and use it in GitHub Desktop.
function getRangePos(obj){
var Pos = 0; //ie
if (document.selection){
obj.focus();
var Sel = document.selection.createRange();
Sel.moveStart('character', -obj.value.length);
Pos = Sel.text.length;
}else if (obj.selectionStart || obj.selectionStart == '0'){
Pos = obj.selectionStart;
}
return Pos;
}
function setRangePos(obj, pos){
if (obj.setSelectionRange){
obj.focus();
obj.setSelectionRange(pos,pos);
}else if (obj.createTextRange){
var range = obj.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
function get_click(){
var obj = document.getElementById('soruce_id');
var pos = getRangePos(obj);
document.getElementById('info').innerHTML = document.getElementById('info').innerHTML + 'Pos:' + pos + '\n';
obj.focus();
}
function set_click(){
var obj = document.getElementById('soruce_id');
var num = document.getElementById('pos_num');
var numVal = parseInt(num.value);
num.value = numVal;
if (numVal > 0){
setRangePos(obj, numVal);
}
obj.focus();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment