是否可以动态获取固定宽度的文本的最后一行? [英] Is it possible to dynamically get the last line of a text fitted in a fixed width?

查看:82
本文介绍了是否可以动态获取固定宽度的文本的最后一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是示例

<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>

这个div的宽度是200px,我需要抓住我在浏览器中看到的最后一行,用跨度包裹它。例如< span>它超过2000年。< / span> 在我的情况下。

this div is 200px width, and I need to catch the last line I can see in the browser, wrapping it with a span. Such as <span>it over 2000 years old.</span> in my case.

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

Is this possible with jquery/javascript? Or at least get the lenght of this "last" line.

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

I think I find a good way: https://jsfiddle.net/qqkxyq42/2/

推荐答案

这很有效。逐字逐句计算宽度

This works. Goes word by word calculating the width

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>

这篇关于是否可以动态获取固定宽度的文本的最后一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆