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

接下来直接上代码:
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();
}
})
})
本文介绍如何使用JavaScript实现文字的收起展开功能。通过示例代码展示HTML和JS部分,帮助开发者快速理解并应用到实际项目中。
760

被折叠的 条评论
为什么被折叠?



