2015-11-07 27 views
0

我正在尋找在包裝在div中的段落的最後一行創建動畫效果。它擁有了其中的一些環節,所以它看起來有點像這樣:使用Javascript選擇段落的最後一行

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

那麼,曾經的最後一行突破發生在頁面加載,我要選擇一個範圍的最後一行給它的效果。

我希望不要有使用jQuery即使我可能需要...

回答

0

嘗試使用.textContentString.prototype.split()RegExp/\n/Array.prototype.slice()與參數-1選擇最後一個新行字符,String.prototype.replace()替換選定的文本內div用具有選定的span元件文本

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>

0

當你標記jQuery的..這是一個jQuery代碼..但一定要包括jQuery的第一

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

另一DEMO用了slideDown效果