Getting a specific line using jQuery

前端 未结 3 1885
慢半拍i
慢半拍i 2020-12-18 11:34

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 lin

相关标签:
3条回答
  • 2020-12-18 11:50

    you could use javascript's .split() and deliminate by "<br>".

    split tutorial

    0 讨论(0)
  • 2020-12-18 11:54

    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.

    0 讨论(0)
  • 2020-12-18 12:13

    Well, there's a way to guesstimate it, and it's not pretty, but I've used it before.

    The algorithm basically goes like this:

    1. Create a "test" node, absolutely positioned within the block you want to measure.
    2. Put some text in that test node.
    3. Get the height of that test node. (We'll call it H.) This is your estimated height for a line.
    4. Now create a duplicate block, with no text in it.
    5. Iterate through a loop that will -- a) Take the content from the block, and add one word at a time to the new duplicate block. b) Check the height of the block. If the height falls between 4H and 6H, then you are within the range of the 5th line. Append that text to a buffer variable.
    6. Your buffer variable will contain the text that is displayed on the fifth line.

    It's not pretty but it works if you duplicate the elements right.

    0 讨论(0)
提交回复
热议问题