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
|
1 Answer
Reset to default 0You 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
);
};
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745349809a4623764.html
<>
button) . – James Commented Jan 17 at 18:48visibility: hidden;
and take away thetext-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:02scrollWidth
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