问题
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