简体   繁体   中英

How can I find the line-breaks created by word-wrapping in contentEditable or elsewhere?

I'm trying to find the actual number of lines currently displayed to the user by a browser's layout engine. Finding 'hard' breaks, <'br'> tags etc, is easy enough, but I can't find a way to see, in code, what I can count onscreen.

I have searched here, and there are a few questions/answers implying it can't be done, or is at the least very involved, but they are all several years out of date, and perhaps things have changed.

textContent doesn't do it, and using the div's height doesn't work in this application. Maybe there's a jQuery way I'm unaware of?

Divide the height of the whole thing by the height of one character. This method works in IE, Safari, FF and Chrome, though the situation is fairly simple, only one size of font etc, so could do with a more thorough workout before being declared The Right Way; it needs empty node checks etc.

function getLineCount(node) {
    if (node) {
        var range = document.createRange();
        range.setStart(node, 0);
        range.setEnd(node, 1);
        var h1 = range.getBoundingClientRect().height;
        range.setEnd(node, node.length);
        return Math.round(range.getBoundingClientRect().height / h1);
    }
};

Is the Tumbleweed Badge also known as crickets?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM