How to determine the position of "new lines" in the text of an HTML element?

Adding long text inside an HTML element, such as a DIV, the element wraps that text. Just like this question text, actually. How can I take text from such an HTML element and determine where it breaks? that is, where the new row is inserted.

For example, in this field a new line appears after "... like this", one after "... where is it" and two after "... is inserted".

+5
source share
2 answers

So, the problem is actually how to do word wrap in HTML5 canvas :

HTML, / HTML5. , , .fillText() , , "" .

, measureText, . , (ctx2d.measureText(words).width <= containerWidth), . . - fillText .

, HTML \n, \r , HTML, <br \>. , .

:

var paragraphs = textarea.value.split('\n');

:

var paragraphs = [];

// getting all <p> and elements in a typical HTML element
// as well as individual text nodes (they are just DOM-nodes),
// separated by <br /> elements
var innerNodes = nonFormElement.childNodes;

for (var i = 0, len = innerNodes.length; i += 1) {
    // if a sub-element has some text in it,
    // add the text to our list
    var content = innerNodes[i].textContent;
    if (content) {
        paragraphs.push(content);
    }
}
+2

, . , . fiddle


var $text = $('#text'),
    breaks = [],
    top;

// wrap words (\w+) and punctuation (\S+) [well, non-word and non-space]
// in <spans> we can easily identify
$text.html($text.text().replace(/(\w+|\S+)/g, '<span>$1</span>'));

$text.children().each(function() {
    var $this = $(this),
        _top = $this.position().top;

    if (top === undefined) {
        top = _top;
    } else if (top < _top) {
        top = _top;
        // moved a row down
        breaks.push($this.prev());
        $this.prev().css('color', 'red');
    }
});


console.log(breaks);
+1

All Articles