JS如何判断文字被ellipsis了?

发布时间 2023-12-15 09:49:05作者: 阿彬~

在写页面的时候,我们知道想要文本超出宽度后用省略号省略,只需要加上一下的css就行了。

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

如果我们想要当文本被省略的时候,也就是当文本超出指定的宽度后,鼠标悬浮在文本上面才展示popper,应该怎么实现呢?这时候我们可以通过JS来计算。

创建一个block元素来包裹inline元素

这种方法应该是最简单的办法,要点就是外层一定是block元素,内存是inline元素。

<div class="ellipsis box">
  <span class="content">
        有一说一,这件事大家懂得都懂,不懂得,说了你也不明白,不如不说。你们也别来问我怎么了,利益牵扯太大,说了对你们也没什么好处,当不知道就行了,其余的我只能说这里面水很深,牵扯到很多大人物。
  </span>
</div> <style>   .ellipsis { overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
  }
  .box { border: 1px solid gray; padding: 10px;
  }
</style>

通过上面对css和html做的处理,我们可以实现让box元素里面的文字进行ellipisis,同时由于并没有对span.content进行任何overflow的处理,所以该span的offestWidth还是保持不变。

const checkEllipsis = () => {
  const boxEl = document.querySelector(".box");
  const contentEl = document.querySelector(".box .content");
  const computedStyle = getComputedStyle(boxEl);
  const pLeft = computedStyle.paddingLeft;
  const pRight = computedStyle.paddingRight;
  const horizontalPadding = parseFloat(pLeft) + parseFloat(pRight);
  if (boxEl.clientWidth <= contentEl.offsetWidth + horizontalPadding) {
    console.log("存在省略号");
  } else {
    console.log("容器宽度足够,没有省略号了");
  }
};

通过以上JS的计算,我们就可以知道文本什么时候被ellipsis了。