其他分享
首页 > 其他分享> > JS CSS 超出字符省略号,获取字符串实际所占长度,显示文字提示tooltip

JS CSS 超出字符省略号,获取字符串实际所占长度,显示文字提示tooltip

作者:互联网

CSS 超出字符省略号

.a{
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

JS获取字符串实际所占长度

computed: {
  //计算字符串所占宽度
  stringWidth() {
    return function (string) {
      const dom = document.createElement('span') //创建一个span
      dom.style.display = 'inline-block'
      dom.style.fontSize = '14px' //这里的 fontSize 要设置成你字符串所对应的 fontSize ,得到的长度才会正确
      dom.textContent = string
      document.body.appendChild(dom)
      const width = dom.clientWidth
      document.body.removeChild(dom)
      return width
    }
  },
},

超出字符省略号,获取字符串实际所占长度,显示文字提示tooltip

<template>
 <el-tooltip
  :content="string"
  placement="top"
  :disabled="strWidth(string) <= boxWidth('span')"
 >
  <span id="idA" className="classA">{{string}}</span>
 </el-tooltip>
</template>
computed: {
  //计算字符串所占宽度
  strWidth() {
    return function (string) {
      const dom = document.createElement('span')
      dom.style.display = 'inline-block'
      dom.style.fontSize = '14px'
      dom.textContent = string
      document.body.appendChild(dom)
      const width = dom.clientWidth
      document.body.removeChild(dom)
      return width
    }
  },
  //字符串所在元素宽度
  boxWidth() {
    return function (dom) {
      return document.getElementById(dom)?.offsetWidth ?? 0
    }
  },
}
.classA{
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

标签:body,return,string,省略号,dom,tooltip,JS,字符串,document
来源: https://blog.csdn.net/sugerinaflat/article/details/122684246