Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

javascript - How to select nth line of text (CSS/JS)

How to select and apply style on a specific line of text? Like the CSS pseudo-element :first-line, but I want to select any line, not limited to the first.

It seems that it can't be done by using only CSS... Anyway I don't mind a JS solution.


Update:

Well, actually it's only for interest. I'm trying to achieve something like highlighting every even row of a paragraph (for readability, like what everyone does for table rows)...

Pre-formating the text like:

<p>
<span class='line1'>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do </span>
<span class='line2'>eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad </span>
<span class='line3'>minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip </span>
<span class='line4'>ex ea commodo consequat. Duis aute irure dolor in reprehenderit in </span>
<span class='line5'>voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur </span>
<span class='line6'>sint occaecat cupidatat non proident, sunt in culpa qui officia </span>
<span class='line7'>deserunt mollit anim id est laborum.</span>
</p>

...it is ok for me, but how to know where to split? Even if the width of paragraph is given, it is still hard to determine...

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Interesting. You can do something like that with 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); 
  $(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
});

Basically, we wrap each word with a span, and add a class based on the position of the span, whenever the window resizes. I'm sure it can be done more efficiently, but it works as a proof of concept. Of course, for even/odd lines, you can simplify the code.

Edge cases: I didn't test it where the class changes the size or width of the words. It may end up very wrong.

Here it is in action: https://jsbin.com/piwizateni/1/edit?html,css,js,output


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...