js实现文字收起展开功能

本文介绍如何使用JavaScript实现文字的收起展开功能。通过示例代码展示HTML和JS部分,帮助开发者快速理解并应用到实际项目中。

大家在工作中经常会用到文字收起展开的功能,如下图:

 

接下来直接上代码:

html部分

<style>
    .box{
        width: 300px;
        border: 1px solid #000;
        min-height: 32px;
        line-height: 32px;
        max-height: 200px;
        overflow-y: auto;
    }
    .btn{
        color: #1890ff;
        cursor: pointer;
    }
</style>
<body>
    <div class="box">
        <span class="content"> </span>
        <span class="btn">展开</span>
    </div>
</body>

JS部分

$(function(){
    var content = $(".content").html();
    var more = true;
    var hide = function () {
        $(".content").each(function(){
            var maxheight = 100;
            if($(this).text() && $(this).text().length > maxheight){
                $(this).text($(this).text().substring(0,maxheight));
                $(this).html($(this).html() + '...');
                more = true;
                $(".btn").html("展开")
            }else{
                $(".btn").hide();
            }
        })
    }
    hide();
    $(".btn").click(function(){
        if(more){
            $(".content").html(content);
            $(this).html('收起');
            more = false;
        }else{
            hide();
        }
    })
})
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值