最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to Determine if Text is Overflowing & Handle Text Ellipses Removing the Overflow - Stack Overflow

programmeradmin2浏览0评论

I'm trying to write a function that determines whether the text has overflowed (to determine whether I should show a tooltip). How can I handle text ellipsis removing the overflow?

I have:

const isTextOverflowing = (element) => element.scrollWidth > element.clientWidth;

This works in all cases apart from when the text is truncated with ellipsis and is the same number of characters with and without ellipsis and so the text element's scrollWidth equals the clientWidth (and incorrectly returns false).

Note: I add ellipsis to overflowing text with this css className:

clampTextInOneLine: {
    textOverflow: "ellipsis",
    whiteSpace: "nowrap",
    overflow: "hidden",
  },

I'm trying to write a function that determines whether the text has overflowed (to determine whether I should show a tooltip). How can I handle text ellipsis removing the overflow?

I have:

const isTextOverflowing = (element) => element.scrollWidth > element.clientWidth;

This works in all cases apart from when the text is truncated with ellipsis and is the same number of characters with and without ellipsis and so the text element's scrollWidth equals the clientWidth (and incorrectly returns false).

Note: I add ellipsis to overflowing text with this css className:

clampTextInOneLine: {
    textOverflow: "ellipsis",
    whiteSpace: "nowrap",
    overflow: "hidden",
  },
Share Improve this question asked Jan 17 at 18:09 zeena patelzeena patel 112 bronze badges 4
  • Please give an example of the text in the failing case, perhaps with a small html example incorporating the code you have already posted. Use the snippet editor (<> button) . – James Commented Jan 17 at 18:48
  • Maybe you could make the element visibility: hidden; and take away the text-overflow setting; then perform your test; then revert the setting and set visibility back again. It'd require a layout however so it might be a visible "blink" – Pointy Commented Jan 17 at 19:02
  • What browser are you testing in? – Grinn Commented Jan 17 at 19:36
  • you are to test scrollWidth before text-overflow is applied.In other word:, test if it overflows. if it does, apply a class with the text-overflow rules and manage/create your tooltip from there – G-Cyrillus Commented Jan 17 at 21:23
Add a comment  | 

1 Answer 1

Reset to default 0

You can select the node's contents, which gives the correct size even when they are truncated by the parent element:

const isTruncated = (element: Element): boolean => {
  const range = document.createRange();
  range.selectNodeContents(element);
  const elementRect = element.getBoundingClientRect();
  const rangeRect = range.getBoundingClientRect();

  return (
    rangeRect.height > elementRect.height || rangeRect.width > elementRect.width
  );
};

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论