JavaScript controls the text to be displayed for one and a half lines, and ellipses will be displayed beyond the content.

  In the process of front-end development, if the text exceeds one or two lines and the excess part displays ellipsis, it is relatively simple to use CSS to implement it. However, if you want to achieve the text that exceeds one and a half lines or two and a half lines and the excess part displays ellipses, it cannot be achieved using CSS. , but it can be done using javascript . as follows:

  html part:

 style:

  js part:

  The method jsLine(line, className) has been encapsulated here and can be used directly. The line parameter is the number of lines to control the text display. One and a half lines is 1.5, two and a half lines is 2.5, and className is the text class name to be controlled. Remember to use class selectors.
  Implementation principle:
  Use text width/text size = how many characters are in a line, and then how many characters are in a line * number of lines that need to be controlled = number of characters that need to be displayed. Once you have the number of characters that need to be displayed, the rest is simple. Use substr( ) just intercept it.
            
  There will be a problem here. If the current text font-size attribute is not set, dom[0].style.fontSize will not be able to obtain the text size. Some friends may say that if it is not set, it will be the browser's default font. size, but the current text may inherit the font-size attribute of its parent class, which means it is not the browser's default font size. So how should we solve it?
            
  var fontSize=getComputedStyle(className[0],undefined).getPropertyValue("font-size")
  This line of code allows you to get the font size after rendering by the browser. 

Guess you like

Origin blog.csdn.net/qq_21473443/article/details/129841540