需求: 一个有最小高度的 textarea 标签,当文字增多时,可以根据需要自动撑开高度。
固定高度可以设置
rows 属性或者min-height 样式。
- vue 中的用法:
<textarea id="feedback" rows="2" placeholder="请输入您想反馈的问题" v-model="feedback" @input="handleInput"></textarea>
handleInput(e) {
e.target.style.height = 'auto';
e.target.style.height = e.target.scrollHeight + 'px';
}
- 原生 js 或 jQuery 中的用法(类似):
<textarea id="feedback" rows="2" placeholder="请输入您想反馈的问题"></textarea>
// 原生 js
document.querySelector('#feedback').addEventListener('input', function(e) {
e.target.style.height = 'auto';
e.target.style.height = this.scrollHeight + 'px';
// this.style.height = 'auto';
// this.style.height = this.scrollHeight + 'px';
})
// jquery
$('#feedback').on('input', function(e) {
$(e.target).css('height', 'auto').css('height', this.scrollHeight + 'px');
// $(this).css('height', 'auto').css('height', this.scrollHeight + 'px');
});

本文介绍如何使用Vue、原生JS及jQuery实现一个可根据输入文本自动调整高度的Textarea组件,确保良好的用户体验。
3392

被折叠的 条评论
为什么被折叠?



