• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

jQuery实现textarea框高度自适应代码示例

jquery 程序员 7年前 (2019-01-18) 227次浏览 已收录 0个评论

分享一段代码实例,它实现了textarea文本框能够根据内容高度自适应效果。

在默认情况下如果内容超过textarea文本框的高度,那么就会出现滚动条,有时候这有点不够人性化。

如果能够实现高度自适应效果,那就再好不过了。

代码实例如下:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>
			jQuery实现textarea框高度自适应代码示例-搞代码gaodaima.com
		</title>
		<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js">
		</script>
		<script type="text/javascript">
			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(); 
			});
		</script>
	</head>
	<body>
		<textarea id="txt">
			搞代码,学习知识
		</textarea>
	</body>
</html>

 


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:jQuery实现textarea框高度自适应代码示例
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址