我在堆棧中發現了一個解決方案! https://stackoverflow.com/a/18262927/769326
我在調整大小函數中添加了代碼片段。
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);
}
這裏的jsfiddle
我覺得它做的是閃爍的事情,因爲我取代textarea的價值 – dork
我注意到另一件事是,它着重正確時,我打的退格鍵 – dork
哦,我想這是因爲退格按鈕不會觸發按鍵事件,而按鍵事件又不會調用textarea的調整大小功能。如何在輸入字符時複製該效果以避免閃爍? – dork