获取使用jQuery的特定行 [英] Getting a specific line using jQuery
本文介绍了获取使用jQuery的特定行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法搞定,让说,一个模块的内容使用jQuery的5日线(它的第一个字母的偏移量)?
我的意思了视线,浏览器计算的路线,而不是在源$ C $ C就行了。
解决方案
jQuery.fn.line:
jQuery.fn.line =功能(线){
VAR哑= this.clone()。CSS({
顶部:-9999,
左:-9999,
位置:绝对,
宽度:this.width()
})。appendTo(this.parent()),
文= dummy.text()的比赛(/ \ s + \ S + / G)。
VAR的话= text.length,
lastTopOffset = 0,
LINENUMBER = 0,
RET ='',
发现=假;
对于(VAR I = 0; I<字;我++){
dummy.html(
text.slice(0,i)的。加入('')+
文[I] .replace('1 $<跨度/>/(\ S)/,)+
text.slice第(i + 1)。加入('')
);
VAR topOffset =的jQuery('跨',假).offset()顶部。
如果(topOffset!== lastTopOffset){
行号+ = 1;
}
lastTopOffset = topOffset;
如果(行号===线){
发现= TRUE;
RET + =文[I]
} 其他 {
如果(发现){
打破;
}
}
}
dummy.remove();
返回RET;
};
用法:
$('#someParagraph')线(3); // 等等等等等等
如何工作的:
它会遍历整个元素(实际上,该元素的克隆)插入 <跨度/>
每个字中的元素。跨度顶尖偏移缓存 - 当此偏移的变化,我们可以假设我们是在一个新的生产线。
Is there a way to get, let say, the 5th line ( the offset of its first letter ) of a block's content using jQuery ?
I mean the visual line, the browser computed line, and not the line in the source code .
解决方案
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.
这篇关于获取使用jQuery的特定行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文