javascript - 克隆换行时如何防止字溢出?

标签 javascript jquery overflow clone

我在 Wrap each line of paragraph in a span 找到的编码示例遇到问题。 。基本上,它克隆一个 div 中的文本,并输出包裹在另一个 div 中的跨度中的文本。

我遇到的问题是,在克隆过程中,单词会被 chop ,因为单词的长度超过了 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()函数只检查字符串是否足够小以适合给定的宽度,但不关心它是否位于单词的中间。

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

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

关于javascript - 克隆换行时如何防止字溢出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60316349/

相关文章:

javascript - 为什么动画在长时间持续时会出现抖动/断断续续的情况?

javascript - 转换脚本以处理多个实例

html - 停止位置 :absolute element causing ancestor to scroll horizontally

html - flexbox中css网格元素的自动高度

overflow - 为什么这个内联 block 元素被向下推?

在原型(prototype)上定义的 Javascript 属性

javascript - 当您单击一个页面的链接时,更改另一个页面中同一菜单的链接的颜色

javascript - 如何使用 jquery 启用表单的提交按钮?

javascript - ajax从smart-ip获取地理位置json数据

循环内的 JavaScript 闭包——简单实用的例子