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

时光毁灭记忆、已成空白 提交于 2019-12-08 08:19:29

问题


I know I can use CSS :first-line pseudo-elmenent to target and change style of the first line in any block of text (like in this demo: http://jsfiddle.net/6H8sy/). So the first line can be found and targeted.

I was wondering if there's any way to actually select that text to reuse. Something like $(':first-line') (which doesn't work as it is).


回答1:


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)




回答2:


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();


来源:https://stackoverflow.com/questions/21097389/use-first-line-pseudo-element-as-a-jquery-selector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!