Possible to scroll caret into view inside a single HTML text field with JavaScript?

前端 未结 6 678
心在旅途
心在旅途 2021-02-04 03:41

Knowing the jQuery Caret plugin, I\'m still seeing no way to do the following on a single line text box in HTML (i.e. the input:type=text control) with JavaScript:<

6条回答
  •  你的背包
    2021-02-04 03:58

    If you want to put the caret at the end and scroll to the bottom of a textarea, this works perfectly :

    function moveCaretToEnd(el) {
        if (typeof el.selectionStart == "number") {
            el.selectionStart = el.selectionEnd = el.value.length;
        } else if (typeof el.createTextRange != "undefined") {
            el.focus();
            var range = el.createTextRange();
            range.collapse(false);
            range.select();
        }
       setTimeout(function(){
            var pos = $(el).offset().top + $(el).height();
            $('html, body').animate({
                scrollTop: pos
            }, 1000);
        },100);
    }
    
    moveCaretToEnd(document.getElementById("replyBox"));
    

    It will place the caret at the end, and then smoothly scroll the window to the bottom.

提交回复
热议问题