【Javascript】在文本框光标处插入文字并定位光标 (转)

<!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>枫芸志 &raquo; 在文本框的指定位置插入文本并定位光标</title>
<script type="text/javascript">  
function InsertString(tbid, str){
    var tb = document.getElementById(tbid);
    tb.focus();
    if (document.all){
        var r = document.selection.createRange();
        document.selection.empty();
        r.text = str;
        r.collapse();
        r.select();
    }
    else{
        var newstart = tb.selectionStart+str.length;
        tb.value=tb.value.substr(0,tb.selectionStart)+str+tb.value.substring(tb.selectionEnd);
        tb.selectionStart = newstart;
        tb.selectionEnd = newstart;
    }
}
function GetSelection(tbid){
 
    var sel = '';
    if (document.all){
        var r = document.selection.createRange();
        document.selection.empty();
        sel = r.text;
    }
    else{
    var tb = document.getElementById(tbid);
      // tb.focus();
        var start = tb.selectionStart;
        var end = tb.selectionEnd;
        sel = tb.value.substring(start, end);
    }
    return sel;
}
function ShowSelection(tbid){
var sel = GetSelection(tbid);
    if (sel)
        alert('选中的文本是:'+sel);
    else
        alert('未选择文本!');
}
</script>
</head>
<body>
    <form><textarea id="txtContent" cols="50" rows="5">先在本文框中点击鼠标或选择文本以确定光标位置和选取内容。</textarea><br /><br />
    <input type = "button" value = "插入字符串 {Good}" onclick="InsertString('txtContent', '{Good}');"/>
    <input type = "button" value = "插入字符串 {Bad}" onclick="InsertString('txtContent', '{Bad}');"/>    
    <input type = "button" value = "获取选中的文本" onclick="ShowSelection('txtContent');"/><br />
    <div id="tip"></div>
    </form>   
</body>
</html>
posted @ 2015-04-03 00:20  gaving2016  阅读(1364)  评论(0编辑  收藏  举报