任意多行文本超出省略的兼容性解决方案
单行文本超出省略(兼容性高)
.ellipsis {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
多行文本超出省略(Chrome)
/* 以两行为例 */
.ellipsis-2 {
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}
多行文本超出省略(IE)
- 借助工具方法计算真实文本宽度,需要注意的是,
font
字体属性一定要写全,包括weight、size、family
/**
* 使用canvas
* @param {String} text 文本
* @param {String} font 字体 如 'normal 12px Arial'
*/
export function getTextWidth(text, font = "normal 12px Arial") {
const canvas =
getTextWidth.canvas ||
(getTextWidth.canvas = document.createElement("canvas"));
const context = canvas.getContext("2d");
context.font = font;
const metrics = context.measureText(text);
return metrics.width;
}
/**
* 判断当前浏览器是否是ie
*/
export const isIe = () => {
const userAgent = navigator.userAgent;
const isIe =
userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1;
const isIe11 =
userAgent.indexOf("Trident") > -1 && userAgent.indexOf("rv:11.0") > -1;
return isIe11 || isIe;
};
- 经过对比判断,具体使用哪个 class
-
注 1:这里默认宽度为 64,实际使用时,建议检查元素,使用文本所在的元素的实际宽度
-
注 2:这里依旧使用的是两行文本,实际用时,灵活调整即可
/**
* 多行文本控制 - 是否展示省略
* @param {String} text 文本内容
* @param {Number} width 当前单元格的宽度
*/
export function showEllipsis(text, width = 65) {
const textWidth = getTextWidth(` ${text} `);
const res = textWidth > width * 2;
if (res) {
return isIe() ? "ellipsis-2-ie" : "ellipsis-2";
} else {
return "";
}
}
- IE 下的省略号写法
- 为了更好的体验,背景颜色可以设置渐变
.ellipsis-2-ie {
position: relative;
line-height: 16px;
max-height: 32px;
display: inline-block;
overflow: hidden;
background-color: #fff;
&.bg-red {
background-color: #f75666;
}
&::after {
content: "...";
position: absolute;
bottom: 0;
right: 0;
padding-left: 5px;
background-color: inherit;
}
}