键入autoresizing textarea继续聚焦在元素的顶部

dor*_*ork 5 javascript jquery textarea cursor-position autoresize

我有一个扩大的textarea.当textarea已经扩展到足以到达窗口的底部时,主体会闪烁/滚动回到textarea的顶部,除非滚动窗口,否则您无法看到键入的最后一个字符.

样本可以在这个jsfiddle中找到.我尝试在身体上添加一个scrollTo

window.scrollTo(0, document.getElementsByTagName('textarea')[0].getBoundingClientRect().bottom);
Run Code Online (Sandbox Code Playgroud)

如何从窗口计算光标在textarea中的偏移量?我想要获得光标的顶部偏移,如果光标已经超出折叠范围,只需将窗口滚动到其位置.

对此的帮助将不胜感激:)

dor*_*ork 0

我在堆栈中找到了解决方案!/sf/answers/1278404921/

我还添加了在调整大小函数中找到的代码片段。

function resize(e){
var text = _this.value,
    lines = text.split('\n'),
    cursorPosition = $this.getCursorPosition(),
    scrollLeft = window.pageXOffset || (document.documentElement || document.body.parentNode || document.body).scrollLeft,
    scrollTop  = window.pageYOffset || (document.documentElement || document.body.parentNode || document.body).scrollTop;

    for(var i = 0, length = lines.length; i < length; i++){
        if(lines[i].length <= settings.charactersPerLine){
            continue;
        }

        var j = 0,
            space = settings.charactersPerLine;

        while(j++ <= settings.charactersPerLine){
            if(lines[i].charAt(j) === ' '){
                space = j;
            }
        }

        lines[i+1] = lines[i].substr(space) + (lines[i + 1] || '');
        lines[i] = lines[i].substr(0, space);
    }

    _this.value = lines.join('\n');

    if(cursorPosition == text.length){
        setCaretToPos(_this, cursorPosition + 1);
    }
    else{
        setCaretToPos(_this, cursorPosition);
    }

    _this.style.height = elementHeight;
    _this.style.height = _this.scrollHeight + 'px';
    _this.style.overflow = 'hidden';

    window.scrollTo(scrollLeft, scrollTop);
}
Run Code Online (Sandbox Code Playgroud)

这是jsfiddle