跳到主要内容
版本:1.0

单行文字容器省略

1.css 实现

// 文本超出两行显示省略号

:如果设置了 弹性布局 display:flex; 那么下面的的css设置将不起作用

// 单行文本超出显示省略号

div {
width: 300px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}

// 多行行文本超出显示省略号,webkit浏览器使用
div {
width: 300px;
overflow:hidden;
text-overflow:ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}

//通用浏览器
// 文字容器样式设置:
.text {
width: 200px;
position: relative;
line-height: 1.4em;
height: 2.8em; //倍数关系,即行数
overflow: hidden;
}

.text::after {
background: linear-gradient(to right, rgba(255, 255, 255, 0), #ffffff 50%)
repeat scroll 0 0 rgba(0, 0, 0, 0);
bottom: 0;
content: "...";
padding: 0 5px 1px 30px;
position: absolute;
right: 0;
}

是分公司分公司是分公司分公司是分公司分公司是分公司分公司是分公司分公司是分公司分公司是分公司分公司是分公司分公司是分公司分公司是分公司分公司是分公司分公司是分公司分公司是分公司分公司

2.react 组件

支持 css 处理的时候,直接用 css,不支持的时候,通过 js 计算来处理显示文字

import React from "react";

export default class Ellipsis extends React.Component {
static defaultProps = {
line: 2,
ellipsis: "...",
};

constructor(props) {
super(props);

let that = this;

this.text = "";
this.setLineClamp = this.setLineClamp.bind(this);
this.setLineNormal = this.setLineNormal.bind(this);
this.clipText = this.clipText.bind(this);
this.init = this.init.bind(this);
}

componentDidMount() {
this.init();
}

componentDidUpdate() {
this.init();
}

init() {
if ("webkitLineClamp" in document.documentElement.style) {
this.setLineClamp();
this.removeTpl();
} else {
this.setLineNormal();
this.clipText();
}
}

removeTpl() {
try {
this.refs.ellip.removeChild(this.refs.getHeight);
} catch (err) {}
}

setLineNormal() {
Object.assign(this.refs.ellip.style, {
"word-break": "break-all",
"white-space": "normal",
});
}

setLineClamp() {
Object.assign(this.refs.ellip.style, {
overflow: "hidden",
display: "-webkit-box",
webkitBoxOrient: "vertical",
"word-break": "break-all",
"white-space": "normal",
webkitLineClamp: this.props.line,
});
}

clipText() {
let { line, ellipsis, end = () => {} } = this.props;
let ellip = this.refs.ellip;

if (!this.h) {
let getHeight = this.refs.getHeight;
this.h = getHeight.offsetHeight;
this.removeTpl();
}

let getCountHeight = () => {
return parseFloat(getComputedStyle(ellip)["height"], 10);
};

let init = true;

if (!this.text) {
this.text = ellip.textContent;
} else {
ellip.innerHTML = this.text;
}

let text = this.text;
let clip = () => {
let len = 0;
while (Math.floor(getCountHeight() / this.h) > line) {
len += 1;

text = text.slice(0, -1);
ellip.innerHTML = text;

if (!init) {
ellip.innerHTML += ellipsis;
}
}

return len;
};

if (0 < clip()) {
ellip.innerHTML += ellipsis;
init = false;
clip();
}

end();
}

render() {
let { children, className = "" } = this.props;

return (
<div ref="box" className={className}>
<div ref="ellip">
{children}
<span ref="getHeight" style={{ visibility: "hidden" }}>

</span>
</div>
</div>
);
}
}
粉色防晒服刚收到的地对地导弹地对地导弹多大的粉色防晒服刚收到的地对地导弹地对地导弹多大的粉色防晒服刚收到的地对地导弹地对地导弹多大的粉色防晒服刚收到的地对地导弹地对地导弹多大的粉色防晒服刚收到的地对地导弹地对地导弹多大的