日期:2014-05-16  浏览次数:20311 次

===========在JS中查找文本框中的文字并选中=========
需求:有个TextBox,TextMode="MultiLine"
然后有个搜索框text
在搜索框中输入,查找TextBox中的字符并选种.
注意有换行
这个换行问题一直搞不定.
求帮助!!!

支持IE,ff,opera

------解决方案--------------------
楼主说的选中是什么意思?

就是鼠标选中文字 蓝底白字的效果?
------解决方案--------------------
HTML code

<!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>