The text is centered beyond the line break, but the first line after the line break is short and the second line is long

The rendering is like this:

 The big title in the middle is displayed on one line when the PC screen is wider. It is a line of text. On the mobile side, it is line-wrapped, but the bottom line of text is longer than the top line.

The first way I thought of was to insert a newline character, so that a newline is forced when the text has not filled up the width. Then the second line that is squeezed out must have more characters, which can achieve this effect. The specific implementation steps are as follows:

1. Get the screen width and string

2. Traverse the string and insert <br /> after the appropriate length,

  var p_title = $('#blog_title').text();

     $(window).on("resize", function() {
          if ($(this).width() < 480) {     // 宽度小于480时执行的函数
              getNewline(p_title,20)
          }
      });

      function getNewline(val, num) {
              var str = val;
              var number = num;
              var bytesCount = 0;//定义一个变量记录字符串总字节长度
              var s = "";//定义一个空字符串用来接收重新拼接换行之后的字符串
              var pattern = new RegExp("[\u4E00-\u9FA5]+");//汉字的正则表达式
              for (var i = 0; i < str.length; i++) {//遍历原字符串
                  var c = str.charAt(i);//拿到每一个下标对应的值
                  // 统计字符串的字符长度
                  if (pattern.test(c)) {
                      bytesCount += 2;//如果是汉字长度+2
                  } else {
                      bytesCount += 1;//不是汉字长度+1
                  }
                  s += str.charAt(i);//重新拼接字符串
                  // 换行
                  if (bytesCount >= number) {//在指定的长度位置插入换行标签
                      s = s + '<br>';
                      // 重置
                      bytesCount = 0;//保证在下一个相同长度后继续换行
                  }
              }
                  return s;

This is the implementation model I envisioned, but didn't work out. Please give me advice.

Guess you like

Origin blog.csdn.net/m0_56683897/article/details/131942434