让文本框自动适应内容的高度 & 让文本框显示折叠、收放

本文介绍如何使文本框自动适应内容高度并实现折叠、收放功能,通过使用JavaScript和jQuery,结合特定的HTML结构和CSS样式,实现文本框在内容变化时自动调整高度,并能通过点击操作进行内容的展开和收起。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

让文本框自动适应内容的高度 & 让文本框显示折叠、收放

来新的样式需求:要实现下图的效果,点击折叠/收回;

textarea展开折叠

发现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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值