博客
关于我
jquery动态改变textarea高度,高度随着内容增加而自动变高,内容减少而自动变低
阅读量:294 次
发布时间:2019-03-03

本文共 635 字,大约阅读时间需要 2 分钟。

jQuery代码实现自适应高度 textarea

作为开发人员,以下 jQuery 实现可以帮助 textarea 自动调整高度,提升用户体验。以下代码可直接复制使用,需在使用前先注册方法。

jQuery.fn.extend({

autoHeight: function() {
return this.each(function() {
var $this = jQuery(this);
if (!$this.attr('_initAdjustHeight')) {
$this.attr('_initAdjustHeight', $this.outerHeight());
}
_adjustH($this).on('input', function() {
_adjustH($this);
});
});
}
});

function _adjustH(elem) {

var $obj = jQuery(elem);
return $obj.css({
height: $obj.attr('_initAdjustHeight'),
'overflow-y': 'hidden'
}).height(elem.scrollHeight);
}

在项目中使用时,可通过以下方式调用:

$(function() {

$('textarea').autoHeight();
});

该实现通过设置初始高度并响应输入事件,确保 textarea 始终保持合适的尺寸。

转载地址:http://bxyl.baihongyu.com/

你可能感兴趣的文章
Objective-C实现chudnovsky algorithm楚德诺夫斯基算法(附完整源码)
查看>>
Objective-C实现CIC滤波器(附完整源码)
查看>>
Objective-C实现circle sort圆形排序算法(附完整源码)
查看>>
Objective-C实现CircularQueue循环队列算法(附完整源码)
查看>>
Objective-C实现clearBit清除位算法(附完整源码)
查看>>
Objective-C实现climbStairs爬楼梯问题算法(附完整源码)
查看>>
Objective-C实现cocktail shaker sort鸡尾酒排序算法(附完整源码)
查看>>
Objective-C实现cocktailShakerSort鸡尾酒排序算法(附完整源码)
查看>>
Objective-C实现CoinChange硬币兑换问题算法(附完整源码)
查看>>
Objective-C实现collatz sequence考拉兹序列算法(附完整源码)
查看>>
Objective-C实现Collatz 序列算法(附完整源码)
查看>>
Objective-C实现comb sort梳状排序算法(附完整源码)
查看>>
Objective-C实现combinationSum组合和算法(附完整源码)
查看>>
Objective-C实现combinations排列组合算法(附完整源码)
查看>>
Objective-C实现combine With Repetitions结合重复算法(附完整源码)
查看>>
Objective-C实现combine Without Repetitions不重复地结合算法(附完整源码)
查看>>
Objective-C实现conjugate gradient共轭梯度算法(附完整源码)
查看>>
Objective-C实现connected components连通分量算法(附完整源码)
查看>>
Objective-C实现Connected Components连通分量算法(附完整源码)
查看>>
Objective-C实现Convex hull凸包问题算法(附完整源码)
查看>>