How to capture one line of text in a div

后端 未结 4 845
情书的邮戳
情书的邮戳 2021-01-12 14:20

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

4条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-12 14:30

    I thought it would be a good ideea to post the solution I came up with for my own question, because it seems pretty elegant. I didn't have to wrap every word in a span—I just used a visibility:hidden test span to see if the next word in the line was going to cause the line to run past the width of the container before actually adding the next word to the line. As I put together each line I added them to an array. I then just appended each line to the container by iterating over the array. It is live here (at least for a while).

    /*global console, $, OO*/
    /*jslint browser: true*/
    (function (undefined) {
        "use strict";
    
        $(window).on('load', function (event) {
            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 = $('
    ').width('200px').text(str).appendTo('body'); wrapLines($container); }); function wrapLines($container) { var text = $container.text(), words = text.split(' '), lines = [], line = $(''), tmp = $('').css('visibility', 'hidden').appendTo('body'); $container.text(""); $.each(words, function (index, word) { if (tmp.text(line.text() + " " + word).width() < $container.width()) { line.text(line.text() + " " + word); } else { lines.push(line); line.remove(); line = $(''); tmp.text(""); } }); tmp.remove(); for (var kittens = 0 ; kittens < lines.length; kittens++) { lines[kittens].appendTo($container); console.log(lines[kittens].width()); } } }());

提交回复
热议问题