Home > Web Front-end > CSS Tutorial > How Can I Selectively Style Specific Lines of Text Using JavaScript and CSS?

How Can I Selectively Style Specific Lines of Text Using JavaScript and CSS?

Patricia Arquette
Release: 2024-11-28 17:23:11
Original
516 people have browsed it

How Can I Selectively Style Specific Lines of Text Using JavaScript and CSS?

Selecting and Styling Specific Text Lines with CSS and JavaScript

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();
});
Copy after login

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:

  1. Include the jQuery library.
  2. Wrap your text in a paragraph element with an ID or class for selection.
  3. Add the provided script to your page.
  4. Resize the window to see the line classes being applied to each span element.

Additional Notes:

  • Adjust the logic for specific line selection, such as selecting only even or odd lines.
  • Consider potential issues with classes altering word size or width.
  • Check the provided JSBin demo for a working example.

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template