日期:2014-05-16 浏览次数:20426 次
<!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>
<style>
html,body{width:100%;height:100%}
</style>
</head>
<body>
<textarea id='txtText' cols=50 rows=6>
我
想
页
面
加
载
的
时
候
</textarea>
</body>
<script>
var txt = "时";
var txtText = document.getElementById('txtText');
var start = txtText.value.replace(/\r\n/ig,'$').indexOf(txt); // IE 换行符 \r\n 需要处理一下
var end = start + txt.length;
setSelectRange(txtText,start,end);
/**
* 设置textarea的选中区域
*/
function setSelectRange( textarea, start, end )
{
if ( typeof textarea.createTextRange != 'undefined' )// IE
{
var range = textarea.createTextRange();
// 先把相对起点移动到0处
range.moveStart( "character", 0)
range.moveEnd( "character", 0);
range.collapse( true); // 移动插入光标到start处
range.moveEnd( "character", end);
range.moveStart( "character", start);
range.select();
} // if
else if ( typeof textarea.setSelectionRange != 'undefined' )
{
textarea.setSelectionRange(start, end);
textarea.focus();
} // else
}
</script>
</html>