preface

A picture wins thousands of words ~, king of Glory wechat area 100 miles keep request stack ~

Origin is due to the need to do in early August, which involves the text click to expand the effect, looks very simple, but because it is compatible with IE so it can really cost some effort ~, now requires more than two lines with ellipsis and display text, like this:

implementation

  1. Implementation Method 1:
  • getClientRects()

GetClientRects () has a few shortcomings. First, the page must be rendered, then the DOM element must be retrieved, and the current line count can be recalculated by reducing the current string length. Until the number of lines less than 2 exceeds the ellipsis. But I didn’t use it this way, because the looping list involves the ref, and every render puts the ref array in, so I didn’t use it, but it worked.

  • code
<div > <span class=" TXT "> I'm a little text, I'm a little text, I'm a little text I'm a little text, I'm a little text I'm a little text I'm a little text, I'm a little text I'm a little text, I'm a little text I'm a little text, </span> </div> <script> let res = document.querySelector(".txt").getClientRects(); console.log('res', res); </script> </body>Copy the code

2. The idea of method 2 is to calculate the length of the current text content and compare it with the length of the container, which needs to be multiplied by 2 because it is displayed beyond two lines. So how do you get the length of the current text content? At first, I calculated the length of the text by myself, but the calculation was not accurate. Then I found a method on the Internet, which can accurately calculate the width of the current content area, and the effect can be achieved:

@param font{String}: Prototype. PxWidth = function(font) {// re-use canvas object for better performance var canvas = String.prototype.pxWidth.canvas || (String.prototype.pxWidth.canvas = document.createElement("canvas")), context = canvas.getContext("2d"); font && (context.font = font); var metrics = context.measureText(this); return metrics.width; }Copy the code

The last

If you want to post your code, see if anyone sees it, if anyone wants to post it again. Actually, the best way to do it is to use CSS for higher performance.