Selecting and styling specific lines of text may seem straightforward with CSS's :first-line pseudo-element, but what if you need to target any line within the text?
While pure CSS doesn't offer a way to select arbitrary lines, JavaScript can fill the gap.
One approach using JavaScript is to wrap each word in a span element and assign a unique class based on the span's position in the text. Here's the code:
$(function(){ var p = $('p'); var words = p.text().split(' '); var text = ''; $.each(words, function(i, w){ if($.trim(w)) text = text + '<span>' + w + '</span> ' } ); //each word p.html(text); $(window).resize(function(){ var line = 0; var prevTop = -15; $('span', p).each(function(){ var word = $(this); var top = word.offset().top; if(top!=prevTop){ prevTop=top; line++; } word.attr('class', 'line' + line); });//each });//resize $(window).resize(); //first one });
This code essentially breaks the text into individual words, wraps them in spans with CSS classes, and assigns class names based on the span's line position as the browser window is resized.
To highlight every even line of a paragraph, you can modify the code:
$('span.even, span.odd').css({ 'background-color' : '#ccc' });
It's important to note that edge cases, such as class name changes affecting word size or width, may impact the accuracy of the script.
The above is the detailed content of How Can I Target and Style Specific Lines of Text in CSS and JavaScript?. For more information, please follow other related articles on the PHP Chinese website!