单行
网上说的方法也大多都是这种的,用css
的text-overflow
属性
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
p{
width: 100px;
background-color: burlywood;
}
</style>
</head>
<body>
<p>123456789bjkdhkwjiwojojso</p>
</body>
</html>
一个单行的p标签
p的宽度是100px,现在文字的长度超过了。
只要加上:
p{
width: 100px;
background-color: burlywood;
overflow: hidden;/* 超出的部分隐藏起来 */
text-overflow: ellipsis;/* 超出的部分用省略号代替 */
white-space: nowrap;/*规定不换行*/
}
多行
在一个div中写入内容:
div{
width: 400px;
overflow: hidden;/* 超出的部分隐藏起来 */
text-overflow: ellipsis;/* 超出的部分用省略号代替 */
display: -webkit-box;/* 将对象以伸缩盒子模型表示 */
-webkit-line-clamp: 3;/* 想要显示的行数 */
-webkit-box-orient: vertical;/* 设置或检索盒子对象的子元素的排列方式 */
}
不过这个css部分中的-webkit-box-orient: vertical;
有时候编译后会消失,是浏览器的问题,最简单的方法就是把它写在内嵌式里面就行了。
这种的还可以用js来隐藏:
// 用id获取对象
var introduction_solid = document.querySelector("div");
// slice() 方法可从已有的数组中返回选定的元素,截断效果。
// 此处需要根据需求自行修改slice()的值,以达到要显示的内容
var demoHtml = introduction_solid.innerHTML.slice(0,600)+'...';
// 填充至指定位置
introduction_solid.innerHTML = demoHtml;
这种的也可以。