Home >Web Front-end >CSS Tutorial >How Can JavaScript Style Specific Lines of Text Like CSS\'s `:first-line` but for Any Line?

How Can JavaScript Style Specific Lines of Text Like CSS\'s `:first-line` but for Any Line?

Barbara Streisand
Barbara StreisandOriginal
2024-11-18 21:48:02304browse

How Can JavaScript Style Specific Lines of Text Like CSS's `:first-line` but for Any Line?

Selecting Specific Text Lines with JavaScript

How can we style specific lines of text, similar to the :first-line CSS pseudo-element, without limiting it to just the first line?

While CSS alone is insufficient for this task, JavaScript offers a solution.

JavaScript Implementation:

We can wrap each word in a span element using JavaScript:

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

To determine the line number for each span, we use the Window's resize event to calculate the vertical position of each span:

  $(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 

Highlighting Even/Odd Rows:

For highlighting even/odd rows, the code can be simplified to:

  $(window).resize(function(){ 

    $('span', p).each(function(){ 
      var word = $(this); 
      var top = word.offset().top; 
      var line = Math.floor(top / 20);
      word.attr('class', (line % 2 == 0 ? 'even' : 'odd'));
    });//each
  });//resize 

Considerations:

This method assumes that words do not wrap within the same line, and changes in the class may affect the size or width of the words.

Example:

[Click here](https://jsbin.com/piwizateni/1/edit?html,css,js,output) for a working demonstration.

The above is the detailed content of How Can JavaScript Style Specific Lines of Text Like CSS\'s `:first-line` but for Any Line?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn