Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
971 views
in Technique[技术] by (71.8m points)

javascript - Getting a specific line using jQuery

Is there a way to get, let say, the 5th line ( the offset of its first letter ) of a block's content using jQuery ?

I mean the visual line, the browser computed line, and not the line in the source code .

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

jQuery.fn.line:

jQuery.fn.line = function(line) {

    var dummy = this.clone().css({
            top: -9999,
            left: -9999,
            position: 'absolute',
            width: this.width()
        }).appendTo(this.parent()),
        text = dummy.text().match(/S+s+/g);

    var words = text.length,
        lastTopOffset = 0,
        lineNumber = 0,
        ret = '',
        found = false;

    for (var i = 0; i < words; ++i) {

        dummy.html(
            text.slice(0,i).join('') +
            text[i].replace(/(S)/, '$1<span/>') +
            text.slice(i+1).join('')
        );

        var topOffset = jQuery('span', dummy).offset().top;

        if (topOffset !== lastTopOffset) {
            lineNumber += 1;
        }

        lastTopOffset = topOffset;

        if (lineNumber === line) {

            found = true;
            ret += text[i];

        } else {

            if (found) {
                break;
            }

        }

    }

    dummy.remove();
    return ret;

};

Usage:

$('#someParagraph').line(3); // blah blah blah

Example: http://jsbin.com/akave

How it works:

It goes through the entire element (actually, a clone of the element) inserting a <span/> element within each word. The span's top-offset is cached - when this offset changes we can assume we're on a new line.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...