让文本框自动适应内容的高度 & 让文本框显示折叠、收放
来新的样式需求:要实现下图的效果,点击折叠/收回;
发现textarea对象有个属性scrollHeight,表示滑动高度;按照与文本框样式的高度之间的关系,就可以解决上述两个问题。
一、让文本框实现上图折叠/缩回
<div class="note-textarea">
<textarea name="" id="resizeText" ></textarea>
<div class="note-open" "openCloseText()"></div>
</div>
// 样式请根据自己实际进行调整
.note-text {
font-weight: bold;
color: #333;
margin-bottom: 5px;
}
.note-textarea {
width: 98%;
/* height: 120px; */
border: 1px solid #f2f2f2;
border-radius: 10px 10px 10px 10px;
}
.note-textarea textarea{
width: 100%;
height: 80px;
border-radius: 10px 10px 10px 10px;
border: 1px solid #fff;
overflow:scroll;
overflow-y:hidden;
overflow-x:hidden;
}
.note-open {
width: 100%;
height: 20px;
background:#eaeaea url('../../static/img/icon_up_down.png') no-repeat center center;
/* background-color: #eaeaea; */
border-radius: 0px 0px 10px 10px;
}
// 记得引入jQuery
<script>
var opentextShow = false; //全局变量
openCloseText () {
opentextShow = !opentextShow;
if(opentextShow) {
$("#resizeText").height($("#resizeText")[0].scrollHeight);
}else {
$("#resizeText").height("80px");
}
}
</script>
二、让文本框自动使用内容的高度
摘自:https://xp9802.iteye.com/blog/2102441
此篇文档写的已经很详细,明显了,为了保存下来作为自己的收藏,下面将展示复制文本。
方法一:
<textarea rows=1 cols=40 style='overflow:scroll;overflow-y:hidden;;overflow-x:hidden'
"window.activeobj=this;this.clock=setInterval(function(){activeobj.style.height=activeobj.scrollHeight+'px';},200);" "clearInterval(this.clock);"></textarea>
方法二:
<script>
var agt = navigator.userAgent.toLowerCase();
var is_op = (agt.indexOf("opera") != -1);
var is_ie = (agt.indexOf("msie") != -1) && document.all && !is_op;
function ResizeTextarea(a,row){
if(!a){return}
if(!row)
row=5;
var b=a.value.split("\n");
var c=is_ie?1:0;
c+=b.length;
var d=a.cols;
if(d<=20){d=40}
for(var e=0;e<b.length;e++){
if(b[e].length>=d){
c+=Math.ceil(b[e].length/d)
}
}
c=Math.max(c,row);
if(c!=a.rows){
a.rows=c;
}
}
</script>
<textarea style="overflow: hidden; font-family: Verdana,Arial; font-style: normal; font-size: 13px; line-height: normal; " rows="4" cols="30" "javascript:ResizeTextarea(this,4);" "javascript:ResizeTextarea(this,4);" "javascript:ResizeTextarea(this,4);"></textarea>