<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="
http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script>
function GetCursorPosition()
{
// HERE txt is the text field name
var obj=document.getElementById('textarea');
var CurPos = 0;
//FOR IE
if (document.selection)
{
obj.focus ();
var Sel = document.selection.createRange();
Sel.moveStart ('character', -obj.value.length);
CurPos = Sel.text.length;
}
// For Firefox
else if (obj.selectionStart == '0')
CurPos = obj.selectionStart;
return CurPos;
}
function SetCursorPosition(pos)
{
// HERE txt is the text field name
var obj=document.getElementById('textarea');
//FOR IE
if(obj.setSelectionRange)
{
obj.focus();
obj.setSelectionRange(pos,pos);
}
// For Firefox
else if (obj.createTextRange)
{
var range = obj.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
</script>
</head>
<body>
<form id="form1" name="form1" method="post" action="">
<textarea name="textarea" id="textarea" cols="45" rows="5">Basically when we want to create an editor like interface then set or get cursor postion is one of the most important task. Here i want to share two cross-browser supported javascript methods which will meet your requirements To Set cursor position into a TextArea & To Get cursor position from TextArea:</textarea>
<br />
<br />
<input type="button" name="button" id="button" value="Button" onclick="SetCursorPosition(8)" />
</form>
</body>
</html>
这个程序可以在firefox下正常设置光标位置