标签:dev inpu 文字 row 就会 arc nts func image
textarea高度自适应
有时候写表单的时候,会有一个 备注框textarea。
因为textarea不支持自适应高度,就是定好高度或者是行数之后,超出部分就会显示滚动条,看起来不美观。
我们需要美观实现的效果:默认显示一行。当输入的文字超过一行或者输入Enter时,
输入框的高度会随着改变,直到输入完毕。也就是要实现textarea的高度自适应

=========================================================
方案A:用div来模拟textarea实现的,用CSS控制样式,不用JS。
而用DIV来模拟时,首先遇到的问题是:div怎么实现输入功能?
一个普通的block元素上加个contenteditable="true"就实现编辑,出现光标了。
如<div contenteditable="true"></div>
<div class="test-textarea" contenteditable="true" ><br /></div>
.test-textarea {
	width: 400px;
	min-height: 26px;
	line-height: 20px;
	_height: 30px;
	/* max-height: 150px;*/
	margin-left: auto;
	margin-right: auto;
	padding: 3px;
	outline: 0;
	border: 1px solid #ccc;
	font-size: 12px;
	word-wrap: break-word;
	overflow-x: hidden;
	overflow-y: auto;
	-webkit-user-modify: read-write-plaintext-only;
	border-radius: 4px;
}
===================================================
方案B:Js实现textarea自适应
.text-adaption {
				width: 300px;
				height: 34px;
				overflow: hidden;
				padding: 5px 10px;
				resize: none;
				line-height: 24px;
				font-size: 12px;
				color: #666;
				border: 1px solid #ccc;
				outline: 0 none;
				border-radius: 3px;
				box-sizing: border-box;
			}
<textarea id="text-adaption" class="text-adaption" rows="1"></textarea>
<script>
	function $(id) {
		return document.getElementById(id);
	}
	$("text-adaption").onkeyup = function() {
		this.style.height = ‘auto‘;
		this.style.height = this.scrollHeight + "px";
	}
</script>
===========================================
.text-adaption {
				width: 300px;
				height: 34px;
				overflow: hidden;
				padding: 5px 10px;
				resize: none;
				line-height: 24px;
				font-size: 12px;
				color: #666;
				border: 1px solid #ccc;
				outline: 0 none;
				border-radius: 3px;
				box-sizing: border-box;
			}
<textarea id="text-adaption" class="text-adaption" rows="1" ></textarea>
		<textarea  class="text-adaption" rows="1" ></textarea>
<textarea class="text-adaption" rows="1" ></textarea
$(function(){
	function getClass(c){
		return document.getElementsByClassName(c);
	}
	var obj=getClass("text-adaption");
	var len=obj.length;
	
	for(var i=0;i<len;i++){
		obj[i].onkeyup = function() {
			this.style.height = ‘auto‘;
			this.style.height = this.scrollHeight + "px";
		};
	}
	
});
=================================================
标签:dev inpu 文字 row 就会 arc nts func image
原文地址:http://www.cnblogs.com/leshao/p/6851897.html