Problem:
How can you selectively target and stylize a specific line of text in a document? The :first-line CSS pseudo-element allows you to target the first line, but is there a way to select any line?
JavaScript Solution:
Since CSS alone cannot achieve this, a JavaScript solution is necessary. Consider the following approach:
$(function() { var p = $('p'); var words = p.text().split(' '), text = '', line = 0; $.each(words, function(i, w) { if ($.trim(w)) text += '<span>' + w + '</span> '; }); p.html(text); $(window).resize(() => { var prevTop = -15; $('span', p).each(function() { var top = $(this).offset().top; if (top !== prevTop) { prevTop = top; line++; } $(this).attr('class', 'line' + line); }); }); $(window).resize(); });
Explanation:
This solution dynamically wraps each word in a span element, and assigns a line class to each span based on its position. When the window is resized, the script adjusts the line classes to ensure each line is appropriately identified.
How to Use:
Additional Notes:
The above is the detailed content of How Can I Selectively Style Specific Lines of Text Using JavaScript and CSS?. For more information, please follow other related articles on the PHP Chinese website!