3 回答
TA贡献1895条经验 获得超3个赞
需要配置JS来判断文字内容是否超过设定的容器的初始高度,如果超过就设置折叠的CSS否者不设置
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.container{
position: absolute;
left:10px;
right:10px;
width: 200px;
border: 1px solid red;
position: relative;
}
.content{
font-size: 16px;
line-height: 1.5;
width: 100%;
color: #556170;
word-break: break-all;
text-align: justify;
margin: 0;
position: relative;
}
.collapse .content::after{
content: ' ... ';
position: absolute;
right: 0;
bottom: 0;
background: linear-gradient(to right, transparent, #ffffff 50%);
padding-left: 20px;
}
.collapse .expand-collapse::after{
content: '展开';
display: block;
color:red;
width: 100%;
text-align: right;
}
.expand .expand-collapse::after{
content: '收缩';
display: block;
color:red;
width: 100%;
text-align: right;
}
.collapse .content{
overflow: hidden;
height: 50px;
padding: 0;
margin: 0;
}
</style>
</head>
<body>
<div class="container">
<p class="content ">当前的实现是截取固定长度的文本,使之最多显示三行,现在遇到一个问题是,文本长度相同,文本
全是中文 和 不全是中文 所显示的行数是不同,有没有什么好的方式可以适应</p>
<div class="expand-collapse"></div>
</div>
<script>
var expandCollapseDiv;
var containerBoundingClientRect=document.querySelector(".container").getBoundingClientRect();
var contentBoundingClientRect=document.querySelector(".content").getBoundingClientRect();
if(containerBoundingClientRect.height>50){
document.querySelector(".container").setAttribute("class","container collapse");
}else{
document.querySelector(".container").setAttribute("class","container");
document.querySelector(".container").removeChild(document.querySelector(".expand-collapse"))
}
document.querySelector(".container").addEventListener("click",function(){
if(!expandCollapseDiv){
expandCollapseDiv=document.querySelector(".expand-collapse");
}
console.log(event.target);
if(event.target===expandCollapseDiv){
if(document.querySelector(".container").getAttribute("class").split(" ").indexOf("collapse")!==-1){
document.querySelector(".container").setAttribute("class","container expand");
}else{
document.querySelector(".container").setAttribute("class","container collapse");
}
}
},false);
</script>
</body>
</html>
添加回答
举报