在 UniApp 中,要实现 textarea 自动高度并设置最大高度,可以通过动态计算内容高度并绑定样式来实现。以下是具体步骤和代码示例:
实现思路
- 使用
textarea 组件的 @input 事件监听输入内容变化。
- 在事件处理函数中,通过
uni.createSelectorQuery() 获取 textarea 的实例,动态计算内容高度。
- 根据内容高度调整
textarea 的高度,同时设置最大高度限制。
- 使用
style 绑定动态高度值。
代码示例
<template>
<view>
<textarea
:style="{ height: textareaHeight + 'px', 'max-height': maxHeight + 'px', overflow: 'auto' }"
@input="onInput"
placeholder="请输入内容"
></textarea>
</view>
</template>
<script>
export default {
data() {
return {
textareaHeight: 40, // 初始高度
maxHeight: 200 // 最大高度
};
},
methods: {
onInput(event) {
// 延迟执行以确保内容已渲染
setTimeout(() => {
const query = uni.createSelectorQuery().in(this);
query.select('textarea').boundingClientRect(data => {
if (data) {
// 计算新高度,不超过最大高度
let newHeight = Math.min(data.height, this.maxHeight);
this.textareaHeight = newHeight;
}
}).exec();
}, 0);
}
}
};
</script>
注意事项
- 延迟计算:使用
setTimeout 确保内容渲染后再获取高度。
- 最大高度限制:通过
Math.min 确保高度不超过设定值。
- 样式绑定:使用
:style 动态绑定高度和最大高度,overflow: auto 允许内容超出时滚动。
优化建议
- 如果内容高度变化频繁,可考虑防抖处理以减少计算次数。
- 测试不同平台(如微信小程序、H5)的兼容性,确保
boundingClientRect 正常返回高度。
通过以上方法,即可实现 textarea 的自动高度调整并限制最大高度。