background

When text overflow shows ellipsis is one of indispensable skill in each front-end developer, but after text overflow ellipsis display will not be able to see the complete content, this time you can use the title attribute labels, or some UI component library tooltip component, when the mouse moved to balloons in elements and shows a complete content.

A common practice for front-end engineers is to keep the prompt bubbles alive, regardless of whether the text overflows or not. However, in some scenarios, the demand side requires that the mouse will not display the prompt bubble when the text does not overflow, and the prompt bubble will be displayed only when the text overflows.

Needs to summarize

When the text does not overflow, there is no prompt bubble when the mouse moves into the text overflow, but when the mouse moves into the display prompt bubble.

Realize the principle of

  1. Gets the width of the enclosing text element
  2. Adds a mouse-over event to the element
  3. Each time the mouse moves in, determine whether the element width meets the requirements
  4. If not, add bubbles, otherwise not

The implementation code

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta  name="viewport" content="width=device-width, < span style> div {width: 100px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } </style> </head> <body> <div> <span> </span> </div> </body> <script> let dDom = document.getElementsByTagName('div')[0]; let sDom = document.getElementsByTagName('span')[0]; let dDomWidth = sDom.parentNode.offsetWidth; let sDomWidth = sDom.offsetWidth; Sdom.addeventlistener ('mouseover', function () {if (sDomWidth > dDomWidth) {dom.title = 'mouseover'; ' } }) </script> </html>Copy the code

conclusion

The key to achieve this requirement is to obtain the element width and a reasonable judgment width.