如何防止克隆和换行时单词溢出?

How to prevent words from overflowing when cloning and wrapping lines?

我在 找到的编码示例有问题。基本上它在 div 中克隆文本并在另一个 div.

中输出包含在跨度中的文本

我遇到的问题是,在克隆过程中,单词被截断,因为单词的长度超过了 CSS 中设置的宽度。

示例:

<span>I’m up to something. Learning is cool, bu</span>
<span>t knowing is better, and I know the key t</span>

有没有办法让文字不溢出?我试过在 css 中设置 overflow:auto 但它无法识别它。

function trimByPixel(str, width) {
  var spn = $('<span style="visibility:hidden"></span>').text(str).appendTo('body');
  var txt = str;
  while (spn.width() > width) { txt = txt.slice(0, -1); spn.text(txt + "..."); }
  return txt;
}

var stri = $(".str").text();

function run(){
var s = trimByPixel(stri, $(".str").width()).trim()
stri = stri.replace(s,"")
$(".result").append("<span>"+s+"</span>");

if(stri.trim().length > 0){
  run();
}
}

run();
$(".str").remove().delay(10);
.str{
  width:300px;
  }
  
  .result span{
  display:block
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="str"> 
I’m up to something. Learning is cool, but knowing is better, and I know the key to success. Bless up. They never said winning was easy. Some people can’t handle success, I can. 
I told you all this before, when you have a swimming pool, do not use chlorine, use salt water, the healing, salt water is the healing. Put it this way, it took me twenty five years to get these plants, twenty five years of blood sweat and tears, and I’m never giving up, I’m just getting started.                                                         
</div>
<div class="result"></div>

问题在于 trimByPixel() 函数,它只检查字符串是否足够小以适合给定的宽度,但不关心它是否正好位于单词的中间。

要知道我们是否要截断一个单词,我们可以检查字符串中的最后一个字符实际上是什么字符。因此,为简单起见,我们可以检查它是否为空 space 如果是,则切断即可。更复杂的测试可以检查它是否是 a-z A-Z 0-9 中的字符。

while (spn.width() > width || txt.charAt(txt.length-1)!=" ")