单行文本溢出
效果:
html
<div>
你好呀!你好呀!你好呀!你好呀!你好呀!你好呀!你好呀!你好呀!你好呀!
</div>
css:
<style>
div{
width: 300px;
border: 1px solid #ccc;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
</style>
多行文本溢出
方法一:基于高度截断
html代码:
<div>
你好呀!你好呀!你好呀!你好呀!你好呀!你好呀!你好呀!你好呀!你好呀!
你好呀!你好呀!你好呀!你好呀!你好呀!你好呀!你好呀!你好呀!你好呀!
</div>
css 代码:
<style>
div{
width: 300px;
border: 1px solid #ccc;
position: relative;
overflow: hidden;
height: 40px;
line-height: 20px;
}
div::after{
content: '...';
position: absolute;
bottom: 0;
right: 0;
}
</style>
方法二:基础行数截断【纯CSS】
html同上
css 代码
<style>
div{
width: 300px;
border: 1px solid #ccc;
-webkit-line-clamp: 2;
display: -webkit-box;
-webkit-box-orient: vertical;
overflow: hidden;
text-overflow: ellipsis;
}
</style>
方法二:基础行数截断【JS实现】
css 代码
<style>
p{
width: 300px;
border: 1px solid #ccc;
position: relative;
overflow: hidden;
line-height: 20px;
}
.p-after::after {
content: '...';
position: absolute;
bottom: 0;
right: 0;
background: -webkit-linear-gradient(left, transparent, #fff 50%);
background: linear-gradient(to right, transparent, #fff 55%);
}
</style>
js 代码
<script>
(function () {
const divEl = document.getElementsByTagName('p')[0];
var lineHeightPro = window.getComputedStyle(divEl).getPropertyValue('line-height');
var lineHeight = lineHeightPro.substring(0, lineHeightPro.indexOf('p'));
var heightPro = window.getComputedStyle(divEl).getPropertyValue('height');
var height = heightPro.substring(0, heightPro.indexOf('p'));
if ((parseInt(height) / parseInt(lineHeight)) > 3) {
divEl.classList.add('p-after');
divEl.style.height = '60px';
} else {
divEl.classList.remove('p-after');
}
})()
</script>