Select the last line of a paragraph using Javascri

2019-09-12 02:07发布

I'm looking to create an animation effect on the last line of a paragraph which is wrapped in a div. It has some links in them so it looks a little like this:

<div id="wrapper"><p>Lorem ipsum dolor sit amet,
 consectetur adipiscing elit. Integer eu dui et erat</p></div> 

So where ever the last line break happens on page load, I want to select the last line with a span to give it the effect.

I would love not to have to use jQuery even though I may need to...

2条回答
戒情不戒烟
2楼-- · 2019-09-12 02:23

while you tagged jquery .. this is a jquery code .. but be sure to include jquery first

var parText = $('#wrapper p').text(); // get text of p
var parSplit = parText.split("\n"); // split text by \n
var lastLine = parSplit[parSplit.length-1]; // get last line
parText.replace(lastLine , ''); // replace last line with nothing
$('#wrapper p').append('<span>'+lastLine+'</span>'); // append the last line with `<span>lastline</span>` and give it a style you need

DEMO

another DEMO with slideDown effect

查看更多
The star\"
3楼-- · 2019-09-12 02:33

Try using .textContent String.prototype.split() with RegExp /\n/ , Array.prototype.slice() with parameter -1 to select last new line character , String.prototype.replace() to replace selected text within div with span element having selected text

var div = document.getElementById("wrapper");
var text = div.childNodes[0].childNodes[0].textContent.split(/\n/).slice(-1)[0];
div.innerHTML = div.innerHTML.replace(new RegExp("("+text+")"), "<span>$1</span>")
div {
  white-space:pre;
}

div span {
  font-size:18px;
  color: purple;
}
<div id="wrapper"><p>Lorem ipsum dolor sit amet,
 consectetur adipiscing elit. Integer eu dui et erat</p></div>

查看更多
登录 后发表回答