如何捕获div中的一行文本 [英] How to capture one line of text in a div

查看:136
本文介绍了如何捕获div中的一行文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看过与此类似的SO帖子,但没有处理我正在寻找什么。说我有一些文本,我把它扔在一个div,并添加一些任意(可能甚至动态)宽度的div。是否有任何方式,我可以捕获和操纵div程序中的文本的单独行(例如,捕获,然后包装每行文本在其自己的span标签或类似这样,这将使我可以操纵单个行)?

I've looked around at similar SO posts related to this, but none deal with exactly what I am looking for. Say I have some text, I throw it in a div, and add some arbitrary (possibly even dynamic) width to that div. Is there any way that I can then capture and manipulate individual lines of text in the div programmaticaly (say, for example, capture and then wrap every line of text in its own span tag or something like this that will enable me to manipulate individual lines)?

我已经能够使用等宽字体来实现这一点,基本上首先每行创建一个span,然后每个span分配相同数量的字符额外的代码,所以单词不会被切断,当然),但我想要能够做到这一点与非等宽字体,这将导致一个问题,当然,因为水平间距的字符不同于非单点字体。 / p>

I have been able to accomplish this using a monospace font and basically first creating one span per line and just assigning the same number of characters per span (with a little extra code so words don't get cut off of course), but I would like to be able to do this with non-monospaced fonts, which will cause an issue of course because horizontal spacing of characters varies for non-monopsaced fonts.

var str = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
    container = $('<div>');
    container.width('100px').html(str).appendTo('body');

希望。这是住在这里。我想知道:

The output of this is pretty much what you expect. It is live here. What I seek to figure out:


  1. 当换行符时,我可以访问的换行符是否自动插入?

  1. Are newline characters that I can access automatically inserted when the line breaks?

属性在DOM我可以进入到操纵div中的一行?

Are there any other mechanisms or properties in the DOM I can hack into to manipulate one line in a div?

有没有另一种方法,我没有能够保留非等宽文本的自然流动的出现,而能够逐行访问文本?如上所述,我已经用单调文本完成了这一点,但是我的方法依赖于单调文本的统一水平间距。 p>

Is there another approach I haven't though of to be able to retain the appearance of natural flow of non-monospaced text while being able to access text line-by-line? As I said above, I have accomplished this with monospaced text, but my approach was dependent on the uniform horizontal spacing of monospaced text.


推荐答案

其他答案的建议让我很好奇,测试,这是我想出的:

The suggestions from the other answers made me curious so i put them to the test, and this is what i came up with:

function wrapLines($container) {
    // get the text from the conatiner
    var text = $container.text();

    // split the text into words
    var words = text.split(' ');

   // wrap each word in a span and add it to a tmp
   var tmp = '';
   tmp += '<span>' + words.join('</span><span>') + '</span> ';

   // remove the text from the container, and replace it with the wrapped words
   $container.html($(tmp));

    // prepare the offset variable and tmp
    var tmp = '';
    var top = null;
    $container.find('span').each(function(index, word) {
        $word = $(word);
        // if this is the first iteration
        if (top == null) {
            // set the top
            top = $word.position().top;
            // open the first line
            tmp = '<span class="line">';
        }

        // if this is a new line (top is bigger then the previous word)
        if (top < $word.position().top) {
            // close the previous line and start a new one
            tmp += '</span><span class="line">';
            // change the top
            top = $word.position().top;            
        }

        // add the content of the word node + a space
        tmp += $word.text() + ' ';
    });
    // close the last line
    tmp += '</span>';

    // remove the content of the conatiner, and replace it with the wrapped lines
    $container.html($(tmp));    
}

我添加了很多评论,但随时可以问清除。

I added plenty of comments, but feel free to ask if something isn't clear.

要查看代码的动作(包括一些花哨的颜色;-)),看看我的小提琴: http://jsfiddle.net/yZnp8/1/

To see the code in action (including some fancy colors ;-) ), have a look at my fiddle: http://jsfiddle.net/yZnp8/1/

编辑

我将来自@orb的代码放在我的解决方案旁边: http: //jsfiddle.net/yZnp8/5/

与Chrome Inspector的快速比较显示,性能差异很大。 @orbs解决方案需要754ms和17MB,而我的解决方案需要136ms和14MB。

A quick comparison with Chrome Inspector shows that there is a big performance diiference. @orbs solution takes 754ms and 17MB while my solution takes 136ms and 14MB.

一点建议,尝试限制DOM操作(我在小提琴上标记它们)。他们减慢你的代码,因为浏览器需要再次渲染您的页面。我只做 2 ,而你 3 + 2x字数+ 1x行数。这可能是解释速度的巨大差异。文本越长,差异就越大。

A little word of advice, try to limit your DOM operations (I marked them in the fiddle). They slow your code down, as the browser needs to render your page all over again. I do only 2, while you do 3 + 2x number of words + 1x number of lines. This is probably what explains the big difference in speed. And the longer the text, the bigger the difference will become.

不试图打破@orb解决方案,只是试图帮助和解释差异...

Not trying to break @orb solution down, just trying to be helpful and explain the differences...

这篇关于如何捕获div中的一行文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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