Use :first-line pseudo-element as a jQuery selector

好久不见. 提交于 2019-12-06 23:40:56
Josh Crozier

Since you can't select the pseudo element itself, you could replicate the behavior of :first-line, to determine the text. I wrote a quick JS function, similar to the one @Kevin B suggests. The function initially determines the height of the element if there is only one line of text present. A for loop is then used to remove a word from the text node until the element's new height equals the initial height. The function then returns with the first-line text.

Example Here - the function is run onLoad, therefore if the window's width changes, the text obviously won't match first-line. You could easily fix this by running the function when the screen is resized.

JavaScript function - no jQuery

function first_line(element) {
    var el = document.getElementById(element), cache = text = el.innerHTML;
    el.innerHTML = 'a'; var initial = el.offsetHeight; el.innerHTML = cache;
    arr = text.split(" ");
    for (var i = 0; i < arr.length; i++) {
        text = text.substring(0, text.lastIndexOf(" "));
        if (el.offsetHeight == initial) {
            var temp = el.innerHTML;
            el.innerHTML = cache;
            return temp;
        }
        el.innerHTML = text;
    }
}

I don't know if I'm re-inventing the wheel here, or not; but this does work. I'm not aware of any jQuery or built-in JS that is able to achieve this. Disregarding browser support, this should also work without any cross-browser styling inconsistencies. It seems to work with any types of padding/borders. (example)

Uder Moreira

I guess this Stackoverflow question is what you are looking for:

getting the first line of text in an element jquery

var first_line = $("#element")
                       .contents()
                       .filter(function() { 
                           return !!$.trim( this.innerHTML || this.data ); 
                       })
                       .first();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!