还有另一个关于这个的帖子,我试过了。但有一个问题:如果你删除内容,文本区域不会缩小。我找不到任何方法将其缩小到正确的大小- clientHeight值返回为文本区域的完整大小,而不是它的内容。
该页面的代码如下:
function FitToContent(id, maxHeight)
{
var text = id && id.style ? id : document.getElementById(id);
if ( !text )
return;
var adjustedHeight = text.clientHeight;
if ( !maxHeight || maxHeight > adjustedHeight )
{
adjustedHeight = Math.max(text.scrollHeight, adjustedHeight);
if ( maxHeight )
adjustedHeight = Math.min(maxHeight, adjustedHeight);
if ( adjustedHeight > text.clientHeight )
text.style.height = adjustedHeight + "px";
}
}
window.onload = function() {
document.getElementById("ta").onkeyup = function() {
FitToContent( this, 500 )
};
}
React的一个示例实现:
const {
useLayoutEffect,
useState,
useRef
} = React;
const TextArea = () => {
const ref = useRef();
const [value, setValue] = useState('Some initial text that both wraps and uses\nnew\nlines');
// This only tracks the auto-sized height so we can tell if the user has manually resized
const autoHeight = useRef();
useLayoutEffect(() => {
if (!ref.current) {
return;
}
if (
autoHeight.current !== undefined &&
ref.current.style.height !== autoHeight.current
) {
// don't auto size if the user has manually changed the height
return;
}
ref.current.style.height = "auto";
ref.current.style.overflow = "hidden";
const next = `${ref.current.scrollHeight}px`;
ref.current.style.height = next;
autoHeight.current = next;
ref.current.style.overflow = "auto";
}, [value, ref, autoHeight]);
return (
<textarea
ref={ref}
style={{
resize: 'vertical',
minHeight: '1em',
}}
value={value}
onChange={event => setValue(event.target.value)}
/>
);
}
ReactDOM.render(<TextArea />, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="app"></div>
一个更简单、更清晰的方法是:
// adjust height of textarea.auto-height
$(document).on( 'keyup', 'textarea.auto-height', function (e){
$(this).css('height', 'auto' ); // you can have this here or declared in CSS instead
$(this).height( this.scrollHeight );
}).keyup();
//和CSS
textarea.auto-height {
resize: vertical;
max-height: 600px; /* set as you need it */
height: auto; /* can be set here of in JS */
overflow-y: auto;
word-wrap:break-word
}
所有需要做的就是将.auto-height类添加到您想要的目标文本区域。
在FF, Chrome和Safari测试。如果这对你不起作用,请告诉我,不管是什么原因。但是,这是我发现的最简单明了的方法。而且效果非常好!: D
我在常见的浏览器中测试了脚本,在Chrome和Safari中失败了。这是因为不断更新的scrollHeight变量。
我已经使用jQuery应用了wrettledgoat脚本,并添加了chrome修复
function fitToContent(/* JQuery */text, /* Number */maxHeight) {
var adjustedHeight = text.height();
var relative_error = parseInt(text.attr('relative_error'));
if (!maxHeight || maxHeight > adjustedHeight) {
adjustedHeight = Math.max(text[0].scrollHeight, adjustedHeight);
if (maxHeight)
adjustedHeight = Math.min(maxHeight, adjustedHeight);
if ((adjustedHeight - relative_error) > text.height()) {
text.css('height', (adjustedHeight - relative_error) + "px");
// chrome fix
if (text[0].scrollHeight != adjustedHeight) {
var relative = text[0].scrollHeight - adjustedHeight;
if (relative_error != relative) {
text.attr('relative_error', relative + relative_error);
}
}
}
}
}
function autoResizeText(/* Number */maxHeight) {
var resize = function() {
fitToContent($(this), maxHeight);
};
$("textarea").attr('relative_error', 0);
$("textarea").each(resize);
$("textarea").keyup(resize).keydown(resize);
}
如果你不需要支持IE8,你可以使用input事件:
var resizingTextareas = [].slice.call(document.querySelectorAll('textarea[autoresize]'));
resizingTextareas.forEach(function(textarea) {
textarea.addEventListener('input', autoresize, false);
});
function autoresize() {
this.style.height = 'auto';
this.style.height = this.scrollHeight+'px';
this.scrollTop = this.scrollHeight;
window.scrollTo(window.scrollLeft,(this.scrollTop+this.scrollHeight));
}
现在你只需要添加一些CSS,你就完成了:
textarea[autoresize] {
display: block;
overflow: hidden;
resize: none;
}
用法:
<textarea autoresize>Type here and I’ll resize.</textarea>
你可以在我的博客文章中阅读更多关于它是如何工作的。