const dom = document.querySelector('.group-field')
const width = dom.offsetWidth - 30// 行宽
const totalNum = val.length // 文本的个数
const fontSizeWidth = window.getComputedStyle(dom, null).fontSize // 字体大小
const num = Math.floor(width / fontSizeWidth.slice(0, -2)) // 一行可以显示多少个字符(纯文本 若不是纯文本会存在误差)
if (totalNum > num) {
const slice = totalNum - num // 截取的长度
const text = val.substring(slice, val.length) // 截取的文字
const str = '...'
const content = str.concat(text) // 拼接
dom.innerHTML = content // 赋值
} else {
dom.innerHTML = val
}
js实现