我们在做项目时,通常会遇到文字太长放不下的情况,这时候我们需要对超长的文字进行…省略隐藏,当鼠标移上去时再显示全部内容。
// 写在 页面 方法 部分
// 这里的 offsetHeight 是返回元素的宽度(包括元素宽度、内边距和边框,不包括外边距)
// let height= this.$refs.init.$el.offsetHeight;
// let height= divDom.VALUE.$el.offsetHeight; // 在Vue3 中的写法
// 这里的offsetHeight可以替换,用来获取其他的属性
// offsetWidth //返回元素的宽度(包括元素宽度、内边距和边框,不包括外边距)
// offsetHeight //返回元素的高度(包括元素高度、内边距和边框,不包括外边距)
// clientWidth //返回元素的宽度(包括元素宽度、内边距,不包括边框和外边距)
// clientHeight //返回元素的高度(包括元素高度、内边距,不包括边框和外边距)
// style.width //返回元素的宽度(包括元素宽度,不包括内边距、边框和外边距)
// style.height //返回元素的高度(包括元素高度,不包括内边距、边框和外边距)
// scrollWidth //返回元素的宽度(包括元素宽度、内边距和溢出尺寸,不包括边框和外边距),无溢出的情况,与clientWidth相同
// scrollHeigh //返回元素的高度(包括元素高度、内边距和溢出尺寸,不包括边框和外边距),无溢出的情况,与clientHeight相同
// 除此之外,还可以获取带有单位的数值
// let height = window.getComputedStyle(this.$refs.init).height;
- 代码示例
interface UnitType {
width: number;
height: number;
}
export const getTextWidth = (text: string, fontSize = 14) => {
// 创建一个元素
const span = document.createElement('span') as HTMLSpanElement;
// 设置一个虚拟元素等于span的宽高
const result: UnitType= { width: 0, height: 0 };
result.width = span.offsetWidth;
result.height = span.offsetHeight;
// 将span元素隐藏
span.style.visibility = 'hidden';
span.style.fontSize = fontSize + 'px';
span.style.display = 'inline-block';
span.style.fontFamily = 'PingFangSC-Regular';
// 将span绑定到dom身上
document.body.appendChild(span);
if (typeof span.textContent !== 'undefined') {
span.textContent = text;
} else {
span.innerText = text;
}
result!.width = parseFloat(window.getComputedStyle(span).width) - result.width;
result!.height = parseFloat(window.getComputedStyle(span).height) - result.height;
span!.parentNode!.removeChild(span); //删除节点
return result;
};
- 使用示例
// title是你传入的文字 Tooltip 是antd的组件
{title && getTextWidth(title).width > 200 ? (
<Tooltip placement="top" title={title}>
<span className={style.hideAllName }>{title}</span>
</Tooltip>
) : (
<span className={style.hideAllName }>{title}</span>
)}
// 样式
.hideAllName {
margin-left: 8px;
font-weight: 700;
font-size: 14px;
// 最主要的是以下四行:
width: 200px; // 这个是超出多宽就出现...省略号
white-space: nowrap; // 不折行
overflow: hidden; // 超出隐藏
text-overflow: ellipsis; //溢出显示省略号
}
- 另一种写法:简易版 ---- 判断字段长度隐藏
export const getTextWidthSecond = (text: string, fontSize: string) => {
const span = document.createElement('span');
span.style.fontSize = fontSize;
span.style.visibility = 'hidden';
span.style.position = 'absolute';
span.style.whiteSpace = 'nowrap';
span.innerText = text;
document.body.appendChild(span);
const width = span.offsetWidth;
document.body.removeChild(span);
return width;
};