我在页面上有一个块元素的集合。它们都有CSS规则white-space, overflow, text-overflow设置,以便溢出的文本被修剪并使用省略号。

但是,并非所有元素都溢出。

有没有办法,我可以使用javascript来检测哪些元素溢出?

谢谢。

添加:示例HTML结构我正在工作。

<td><span>Normal text</span></td>
<td><span>Long text that will be trimmed text</span></td>

SPAN元素总是适合单元格,它们应用了省略号规则。我想检测何时将省略号应用于SPAN的文本内容。


当前回答

我的实现)

const items = Array.from(document.querySelectorAll('.item')); items.forEach(item =>{ item.style.color = checkEllipsis(item) ? 'red': 'black' }) function checkEllipsis(el){ const styles = getComputedStyle(el); const widthEl = parseFloat(styles.width); const ctx = document.createElement('canvas').getContext('2d'); ctx.font = `${styles.fontSize} ${styles.fontFamily}`; const text = ctx.measureText(el.innerText); return text.width > widthEl; } .item{ width: 60px; overflow: hidden; text-overflow: ellipsis; } <div class="item">Short</div> <div class="item">Loooooooooooong</div>

其他回答

对于那些使用(或计划使用)来自Christian Varga的公认答案的人,请注意性能问题。

以这种方式克隆/操作DOM会导致DOM Reflow(请参阅此处关于DOM Reflow的解释),这是非常资源密集型的。

在一个页面上使用Christian Varga的100多个元素的解决方案会导致4秒的回流延迟,在此期间JS线程被锁定。考虑到JS是单线程的,这意味着对最终用户来说有很大的UX延迟。

Italo Borssatto的答案应该是公认的,在我的分析过程中,它大约快了10倍。

e.offsetWidth < e.scrollWidth解决方案并不总是有效。

如果你想使用纯JavaScript,我建议使用这个:

(打印稿)

public isEllipsisActive(element: HTMLElement): boolean {
    element.style.overflow = 'initial';
    const noEllipsisWidth = element.offsetWidth;
    element.style.overflow = 'hidden';
    const ellipsisWidth = element.offsetWidth;

    if (ellipsisWidth < noEllipsisWidth) {
      return true;
    } else {
      return false;
    }
}

初步的。offsetWdith VS le. scrollwidth 这对我很有用! https://jsfiddle.net/gustavojuan/210to9p1/

$(function() {
  $('.endtext').each(function(index, elem) {
    debugger;
    if(elem.offsetWidth !== elem.scrollWidth){
      $(this).css({color: '#FF0000'})
    }
  });
});

这些解决方案都不适合我,所以我选择了一种完全不同的方法。我没有使用带有省略号的CSS解决方案,而是从特定的字符串长度中剪切文本。

  if (!this.isFullTextShown && this.text.length > 350) {
    return this.text.substring(0, 350) + '...'
  }
  return this.text

并显示“更多/更少”按钮,如果长度超过。

  <span
    v-if="text.length > 350"
    @click="isFullTextShown = !isFullTextShown"
  >
    {{ isFullTextShown ? 'show less' : 'show more' }}
  </span>

对于使用e.offsetWidth < e.scrollWidth的人,出现了可以显示全文但仍然有省略号的错误。

这是因为offsetWidth和scrollWidth总是取整这个值。例如:offsetWidth返回161,但实际宽度是161.25。 解决方案是使用getBoundingClientRect

const clonedEl = e.cloneNode(true)
clonedElement.style.overflow = "visible"
clonedElement.style.visibility = "hidden"
clonedElement.style.width = "fit-content"

e.parentElement.appendChild(clonedEl)
const fullWidth = clonedElement.getBoundingClientRect().width
const currentWidth = e.getBoundingClientRect().width

return currentWidth < fullWidth