我在页面上有一个块元素的集合。它们都有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的文本内容。


当前回答

除了italo的答案,还可以使用jQuery来实现。

function isEllipsisActive($jQueryObject) {
    return ($jQueryObject.width() < $jQueryObject[0].scrollWidth);
}

另外,正如Smoky指出的那样,您可能希望使用jQuery outerWidth()而不是width()。

function isEllipsisActive($jQueryObject) {
    return ($jQueryObject.outerWidth() < $jQueryObject[0].scrollWidth);
}

其他回答

如果你有反应,我是这么做的。

<div 
  ref={ref => {
    if (!ref) return
    const isOverflowing = ref.scrollWidth > ref.clientWidth
    if (isOverflowing) {
      // handle what to do next here
    }
  }}
/>

初步的。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'})
    }
  });
});

在比较offsetWidth > scrollWidth时,上面的答案有一个小像素问题。

W3C有一个返回元素的遗留API。scrollWidth值被四舍五入,这导致比较在某些情况下返回false。 如果元素宽度为150px, scrollWidth为150.4px(四舍四入到150),那么即使浏览器在文本中显示省略号,该检查也将返回false。

他们已经尝试更新返回分数像素的api,但由于webcompat,它被恢复了。

有一个使用max-content和getClientRects()的变通方法。 这是一个示例代码,我使用onMouseEnter。 注意,这只在容器的边界为可用宽度的100%时才有效(因此,如果您使用flexbox,您的容器必须为flex: 1例如。

hasEllipsis(elementItem) {
    let scrollWidth = elementItem.scrollWidth;
    
    elementItem.style.width = 'max-content';
    const itemRects = elementItem.getClientRects();

    if (itemRects.length > 0 && itemRects[0].width > scrollWidth) {
        scrollWidth = itemRects[0].width;
    }

    elementItem.style.width = 'auto';
    return scrollWidth > elementItem.clientWidth;
}

文章:

https://bugs.chromium.org/p/chromium/issues/detail?id=980476

https://github.com/w3c/csswg-drafts/issues/4123

除了italo的答案,还可以使用jQuery来实现。

function isEllipsisActive($jQueryObject) {
    return ($jQueryObject.width() < $jQueryObject[0].scrollWidth);
}

另外,正如Smoky指出的那样,您可能希望使用jQuery outerWidth()而不是width()。

function isEllipsisActive($jQueryObject) {
    return ($jQueryObject.outerWidth() < $jQueryObject[0].scrollWidth);
}

此示例显示单元格表上的工具提示,文本被截断。是基于表宽度动态的:

$.expr[':'].truncated = function (obj) {
    var element = $(obj);

    return (element[0].scrollHeight > (element.innerHeight() + 1)) || (element[0].scrollWidth > (element.innerWidth() + 1));
};

$(document).ready(function () {
    $("td").mouseenter(function () {
        var cella = $(this);
        var isTruncated = cella.filter(":truncated").length > 0;
        if (isTruncated) 
            cella.attr("title", cella.text());
        else 
            cella.attr("title", null);
    });
});

演示:https://jsfiddle.net/t4qs3tqs/

它适用于所有版本的jQuery