本文共 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/