jQuery.fn.line:
jQuery.fn.line = function(line) {
var dummy = this.clone().css({
top: -9999,
left: -9999,
position: 'absolute',
width: this.width()
}).appendTo(this.parent()),
text = dummy.text().match(/S+s+/g);
var words = text.length,
lastTopOffset = 0,
lineNumber = 0,
ret = '',
found = false;
for (var i = 0; i < words; ++i) {
dummy.html(
text.slice(0,i).join('') +
text[i].replace(/(S)/, '$1<span/>') +
text.slice(i+1).join('')
);
var topOffset = jQuery('span', dummy).offset().top;
if (topOffset !== lastTopOffset) {
lineNumber += 1;
}
lastTopOffset = topOffset;
if (lineNumber === line) {
found = true;
ret += text[i];
} else {
if (found) {
break;
}
}
}
dummy.remove();
return ret;
};
Usage:
$('#someParagraph').line(3); // blah blah blah
Example: http://jsbin.com/akave
How it works:
It goes through the entire element (actually, a clone of the element) inserting a <span/>
element within each word. The span's top-offset is cached - when this offset changes we can assume we're on a new line.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…