问题:需求中form表单输入框需要根据输入内容动态调整输入框高度。
方案:动态获取textarea元素的scrollHeight属性值,设置到textarea元素的style.height属性中。
这里需要注意的是在获取scrollHeight属性值之前应将height设置为auto,否则获取的高度会受到元素padding等属性值的影响。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div style="display: flex;">
<span>留言:</span>
<textarea name="content" id="contentInput" oninput="handleHeight()"></textarea>
</div>
<script>
function handleHeight() {
//注意,在获取scrollHeight属性值之前应将height设置为auto,否则获取的高度会受到元素padding等属性值的影响
contentInput.style.height = 'auto'
height = contentInput.scrollHeight
contentInput.style.height = `${height}px`
}
</script>
</body>
</html>
vant组件中的解决方案
export function resizeTextarea(
input: HTMLInputElement,
autosize: true | FieldAutosizeConfig
) {
input.style.height = 'auto';
let height = input.scrollHeight;
if (isObject(autosize)) {
const { maxHeight, minHeight } = autosize;
if (maxHeight !== undefined) {
height = Math.min(height, maxHeight);
}
if (minHeight !== undefined) {
height = Math.max(height, minHeight);
}
}
if (height) {
input.style.height = `${height}px`;
}
}
其他解决方案及可行性调研
方案:通过div模拟textarea文本域轻松实现高度自适应,原理是通过HTML5里面的contenteditable属性将div元素变为可编辑内容元素
可行性:该方案是可行的但是在移动端某些机型上会出现不兼容的情况,直接就是div内容不可编辑,所以应慎重使用。