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

如何做到这样的效果?textarea框选中状态,光标在最后
一个button,有点击事件,
一个textarea框

<textarea id="ta"></textarea>
<input type="button" value="点击" onclick="a()">
<script>
function a(){
  document.getElementById("ta").value='12345';
  document.getElementById("ta").focus();
}
</script>

这时让光标在12345的后面,怎么实现?
------解决方案--------------------
<!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>无标题文档</title>
</head>

<body>
<textarea id="ta"></textarea>
<input type="button" value="点击" onclick="a()">
</body>
<script>
function setCaretPosition(tObj, sPos){
    if(tObj.setSelectionRange){
        setTimeout(function(){
            tObj.setSelectionRange(sPos, sPos);
            tObj.focus();
        }, 0);
    }else if(tObj.createTextRange){
        var rng = tObj.createTextRange();
        rng.move('character', sPos);
        rng.select();
    }
}
function a(){
  var oText=document.getElementById("ta");
  oText.value='12345';
  setCaretPosition(oText,oText.value.length);
}
</script>
</html>