是否可以动态获取固定宽度的文本的最后一行?

mar*_*zzz 8 javascript jquery

这是一个例子:

<div class="parent">
  Contrary to popular belief Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old.
</div>
Run Code Online (Sandbox Code Playgroud)

这个div的宽度是200px,我需要抓住我在浏览器中看到的最后一行,用一个跨度包装它.比如<span>it over 2000 years old.</span>在我的情况下.

这有可能与jquery/javascript?或者至少得到这个"最后"行的长度.

编辑:我想我找到了一个好方法:https://jsfiddle.net/qqkxyq42/2/

Ste*_*par 3

这有效。逐字计算宽度

https://jsfiddle.net/stevenkaspar/ht7ostyx/9/

<div

 class="parent" id='text'>
  Contrary to popular belief Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old.
</div>

<script>

function getWidth(pre_space, str, post_space, append_elem){
  var pre = (pre_space) ? '&nbsp;' : '';
  var post = (post_space) ? '&nbsp;' : '';

  var tmp_div = $('<span style="white-space: nowrap;">'+pre+str+post+'</span>');
  append_elem.append(tmp_div);
  var width =  tmp_div.width();
  tmp_div.remove();
  return width;
}
function linkEndLine(elem_id){
  var elem = document.getElementById(elem_id);
  var width = $(elem).width();
  var text = elem.innerText;
  var words = text.split(' ');
  var line_width = 0;
  var current_line = '';
  var lines = [];
  words.map(function(word, index){

    if(line_width == 0){
      line_width += getWidth(false, word, false, $(elem));
    }
    else {
      line_width += getWidth(true, word, false, $(elem));
    }

    if( (line_width / width) > 1){
      lines.push(current_line);

      line_width = getWidth(false, word, false, $(elem)); // new line
      current_line = '';
    }
    current_line += ((current_line != '') ? ' ' : '') + word;

    if(index == (words.length-1)){
      lines.push(current_line);
    }
  })
  var end_index = lines.length - 1;
  lines[end_index] = '<a href="#">'+lines[end_index]+'</a>';
  elem.innerHTML = lines.join(' ');
}
linkEndLine('text');

</script>
Run Code Online (Sandbox Code Playgroud)