<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>文本溢出显示省略号时展示'查看更多'按钮</title>
<style>
.content {
width: 400px;
font-size: 14px;
line-height: 20px;
max-height: 80px;
overflow: hidden;
position: relative;
text-align: justify;
}
.virtual {
position: absolute;
top: -20px;
left: 0;
right: 0;
overflow: hidden;
color: transparent;
/** 文字两端对齐 */
text-align: justify;
}
.more {
position: absolute;
top: 80px;
right: 0;
font-size: 14px;
cursor: pointer;
background-color: white;
color: #484848;
}
.light {
color: #296eff;
}
</style>
</head>
<body>
<div class="content" id="content">
测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试
<div class="virtual" id="virtual">
测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试
<span class="more" id="more"><span id="dot">...</span><span class="light" id="light">更多</span></span>
</div>
</div>
</body>
<script>
const oMore = document.getElementById('more');
const oContent = document.getElementById('content');
const oVirtual = document.getElementById('virtual');
const oLight = document.getElementById('light');
const dot = document.getElementById('dot');
oMore.addEventListener('click', this.moreEvent);
/** 用于判断状态 */
let flag = true
function moreEvent () {
flag ? dealWithStyle('none', 'auto', '收起', '0px', 'none', false) : dealWithStyle('80px', '80px', '更多', '-20px', 'inline-block', true);
flag = !flag
}
function dealWithStyle (maxHeight, top1, text, top2, display, flag) {
oContent.style.maxHeight = maxHeight
oMore.style.top = top1
oLight.innerText = text
oVirtual.style.top = top2
dot.style.display = display
}
</script>
</html>
文本溢出显示省略号时展示‘查看更多‘按钮
最新推荐文章于 2024-03-01 15:53:49 发布