javascript - JS 代码仅在第一组文本上将行换行,对其余文本不执行此操作

标签 javascript jquery text split

我有一个从“Detect browser wrapped lines via javascript ”获得的 JS 代码,它将每一行包装到 <span> 中。 。当有一组文本要包装在 <div> 中时,它会起作用。但如果还有另一组要包装,则不起作用。

您可以在下面的示例代码中看到,第一组文本将起作用(文本上方的绿线),但第二组将不起作用。

$(".emails .multi-items").each(function (i) {
  var $cont = $('#content')

  var text_arr = $cont.text().split(' ');
  
  for (i = 0; i < text_arr.length; i++) {
      text_arr[i] = '<span>' + text_arr[i] + ' </span>';
  }
  
  $cont.html(text_arr.join(''));
  
  $wordSpans = $cont.find('span');
  
  var lineArray = [],
      lineIndex = 0,
      lineStart = true,
      lineEnd = false
  
      $wordSpans.each(function(idx) {
          var pos = $(this).position();
          var top = pos.top;
  
          if (lineStart) {
              lineArray[lineIndex] = [idx];
              lineStart = false;
  
          } else {
              var $next = $(this).next();
  
              if ($next.length) {
                  if ($next.position().top > top) {
                      lineArray[lineIndex].push(idx);
                      lineIndex++;
                      lineStart = true
                  }
              } else {
                  lineArray[lineIndex].push(idx);
              }
          }
  
      });
  
  
  //console.log( lineArray)
  for (i = 0; i < lineArray.length; i++) {
      var start = lineArray[i][0],
          end = lineArray[i][1] + 1;
  
      /* no end value pushed to array if only one word last line*/
      if (!end) {
          $wordSpans.eq(start).wrap('<span class="line_wrap">')
      } else {
          $wordSpans.slice(start, end).wrapAll('<span class="line_wrap">');
      }
  
  };
});
.line_wrap{ border-top: 1px solid green}
.message-contain {padding:35px 0}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="emails">
<ul class="multi-items">
  <div class="message-contain">
      <div id="content">
          Lorem Khaled Ipsum is a major key to success. They will try to close the door on you, just open it. Watch your back, but more importantly when you get out the shower, dry your back, it’s a cold world out there. The other day the grass was brown, now it’s green because I ain’t give up. Never surrender. Every chance I get, I water the plants, Lion! In life you have to take the trash out, if you have trash in your life, take it out, throw it away, get rid of it, major key. You do know, you do know that they don’t want you to have lunch. I’m keeping it real with you, so what you going do is have lunch.
      </div>
  </div>
<div class="message-contain">
  <div id="content">
  Fan luv. You smart, you loyal, you a genius. We don’t see them, we will never see them. In life you have to take the trash out, if you have trash in your life, take it out, throw it away, get rid of it, major key. A major key, never panic. Don’t panic, when it gets crazy and rough, don’t panic, stay calm. The key to more success is to have a lot of pillows. You see the hedges, how I got it shaped up? It’s important to shape up your hedges, it’s like getting a haircut, stay fresh. Let me be clear, you have to make it through the jungle to make it to paradise, that’s the key, Lion!
  </div>
</div>
</ul>
</div>

最佳答案

您的 HTML 无效 - 文档中应该只有一个具有特定 ID 的元素,因此 $('#content') 仅查找第一个 #content.

改用类,然后选择 .content

$(".emails .multi-items .content").each(function() {
  var $cont = $(this);
  // ...

$(".emails .multi-items .content").each(function() {
  var $cont = $(this);

  var text_arr = $cont.text().split(' ');

  for (i = 0; i < text_arr.length; i++) {
    text_arr[i] = '<span>' + text_arr[i] + ' </span>';
  }

  $cont.html(text_arr.join(''));

  $wordSpans = $cont.find('span');

  var lineArray = [],
    lineIndex = 0,
    lineStart = true,
    lineEnd = false

  $wordSpans.each(function(idx) {
    var pos = $(this).position();
    var top = pos.top;

    if (lineStart) {
      lineArray[lineIndex] = [idx];
      lineStart = false;

    } else {
      var $next = $(this).next();

      if ($next.length) {
        if ($next.position().top > top) {
          lineArray[lineIndex].push(idx);
          lineIndex++;
          lineStart = true
        }
      } else {
        lineArray[lineIndex].push(idx);
      }
    }

  });


  //console.log( lineArray)
  for (i = 0; i < lineArray.length; i++) {
    var start = lineArray[i][0],
      end = lineArray[i][1] + 1;

    /* no end value pushed to array if only one word last line*/
    if (!end) {
      $wordSpans.eq(start).wrap('<span class="line_wrap">')
    } else {
      $wordSpans.slice(start, end).wrapAll('<span class="line_wrap">');
    }

  };
});
.line_wrap {
  border-top: 1px solid green
}

.message-contain {
  padding: 35px 0
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="emails">
  <ul class="multi-items">
    <div class="message-contain">
      <div class="content">
        Lorem Khaled Ipsum is a major key to success. They will try to close the door on you, just open it. Watch your back, but more importantly when you get out the shower, dry your back, it’s a cold world out there. The other day the grass was brown, now it’s
        green because I ain’t give up. Never surrender. Every chance I get, I water the plants, Lion! In life you have to take the trash out, if you have trash in your life, take it out, throw it away, get rid of it, major key. You do know, you do know
        that they don’t want you to have lunch. I’m keeping it real with you, so what you going do is have lunch.
      </div>
    </div>
    <div class="message-contain">
      <div class="content">
        Fan luv. You smart, you loyal, you a genius. We don’t see them, we will never see them. In life you have to take the trash out, if you have trash in your life, take it out, throw it away, get rid of it, major key. A major key, never panic. Don’t panic,
        when it gets crazy and rough, don’t panic, stay calm. The key to more success is to have a lot of pillows. You see the hedges, how I got it shaped up? It’s important to shape up your hedges, it’s like getting a haircut, stay fresh. Let me be clear,
        you have to make it through the jungle to make it to paradise, that’s the key, Lion!
      </div>
    </div>
  </ul>
</div>

关于javascript - JS 代码仅在第一组文本上将行换行,对其余文本不执行此操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60482819/

相关文章:

java - 打开短信并在其中放置一个随机数组

javascript - 如何解码 JSON 字符串?

javascript - 如何在 TinyMCE 中创建更新模板变量?

javascript - meteor react 错误: Cannot read property '0' of undefined

javascript - JQuery index() 为第一个元素返回 1 而不是 0

javascript - 图像隐藏时是否下载?

javascript - 使用javascript将文本转换为图像

text - Bootstrap 3 轮播 : Replace indicators with text

javascript - 如何从javascript函数中获取值?

javascript - 原型(prototype)中的全局变量?