首页 > 技术文章 > DIV当textarea使用,在聚焦的时候将光标移动到内容的末尾

adtuu 2015-07-30 09:33 原文

#### DIV当textarea使用,在聚焦的时候将光标移动到内容的末尾 ####

<style type="text/css">
.test_box {
    width: 400px;
    min-height: 120px;
    max-height: 300px;
    _height: 120px;
    margin-left: auto;
    margin-right: auto;
    padding: 3px;
    outline: 0;
    border: 1px solid #a0b3d6;
    font-size: 12px;
    word-wrap: break-word;
    overflow-x: hidden;
    overflow-y: auto;
}
</style>
HTML代码:
<div class="test_box" contenteditable="true"  id="comment"><br /><a href="http://www.baidu.com">aaaa</a></div>

<script>


document.getElementById("comment").onfocus=function(){
    var tObj = document.getElementById("comment");

    var len = tObj.innerHTML.length;
    place_caret_at_end(tObj);
   
}


function place_caret_at_end(el)
    {
        el.focus();
        if (typeof window.getSelection != "undefined" && typeof document.createRange != "undefined")
        {
            var range = document.createRange();
            range.selectNodeContents(el);
            range.collapse(false);
            var sel = window.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
        } else if (typeof document.body.createTextRange != "undefined") {
            var textRange = document.body.createTextRange();
            textRange.moveToElementText(el);
            textRange.collapse(false);
            textRange.select();
        }
    }

</script> 

  

推荐阅读