还有另一个关于这个的帖子,我试过了。但有一个问题:如果你删除内容,文本区域不会缩小。我找不到任何方法将其缩小到正确的大小- 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 )
};
}
我创建了一个小的(7kb)自定义元素,为您处理所有这些调整大小的逻辑。
它可以在任何地方工作,因为它是作为自定义元素实现的。包括:虚拟dom (React, Elm等),服务器端呈现的东西,如PHP和简单乏味的HTML文件。
除了监听输入事件外,它还有一个计时器,每100毫秒触发一次,以确保在文本内容通过其他方式发生变化的情况下,事情仍在工作。
下面是它的工作原理:
// At the top of one of your Javascript files
import "autoheight-textarea";
或作为脚本标记包含
<script src="//cdn.jsdelivr.net/npm/autoheight-textarea@1.0.1/dist/main.min.js"></script>
然后像这样包装你的textarea元素
HTML文件
<autoheight-textarea>
<textarea rows="4" placeholder="Type something"></textarea>
<autoheight-textarea>
React.js组件
const MyComponent = () => {
return (
<autoheight-textarea>
<textarea rows={4} placeholder="Type something..." />
</autoheight-textarea>
);
}
下面是Codesandbox上的一个基本演示:https://codesandbox.io/s/unruffled-http-2vm4c
你可以在这里获取软件包:https://www.npmjs.com/package/autoheight-textarea
如果你只是想看看调整大小的逻辑,你可以看看这个函数:https://github.com/Ahrengot/autoheight-textarea/blob/master/src/index.ts#L74-L85
你可以使用这段代码来计算一个textarea需要的行数:
textarea.rows = 1;
if (textarea.scrollHeight > textarea.clientHeight)
textarea.rows = textarea.scrollHeight / textarea.clientHeight;
在输入和窗口:resize事件上计算它以获得自动调整大小的效果。Angular中的例子:
模板代码:
<textarea rows="1" reAutoWrap></textarea>
auto-wrap.directive.ts
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: 'textarea[reAutoWrap]',
})
export class AutoWrapDirective {
private readonly textarea: HTMLTextAreaElement;
constructor(el: ElementRef) {
this.textarea = el.nativeElement;
}
@HostListener('input') onInput() {
this.resize();
}
@HostListener('window:resize') onChange() {
this.resize();
}
private resize() {
this.textarea.rows = 1;
if (this.textarea.scrollHeight > this.textarea.clientHeight)
this.textarea.rows = this.textarea.scrollHeight / this.textarea.clientHeight;
}
}
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>